我是Python新手,编写了这段代码,用于收集m3u (播放列表)文件中的所有文件,并将它们复制到目录中。
import shutil
import os
import sys
args = sys.argv
#check for m3u file
if len(args) > 1 :
m3ufile = args[1]
else :
print "m3u file must be set"
sys.exit()
#check for destination arg
try :
dest = args[2]
except IndexError :
dest = '.'
#check for destination exists
if os.path.exists(dest) != True and dest != '.' :
os.makedirs(dest)
files = []
with open(m3ufile) as f:
for t in f :
if t[0] != '#' and t not in ['\n','\r\n'] :
t = t.strip()
if t :
files.append(t)
x = 0
fp = len(files)
while x < fp :
print(chr(27) + "[2J")
print str(x + 1) + ' of ' + str(fp) + ' collected!!'
if os.path.exists(files[x]) :
shutil.copy( files[x] , dest)
x = x + 1
print "all files collected in " + dest + " directory.enjoy!"发布于 2015-10-19 10:24:18
不要使用os.path.exists(dest) != True,只需使用if not os.path.exists(dest)。一般来说,测试布尔人就像这样,而不是对它们使用等价。
x = x + 1可以很容易地重写为x += 1。
您还应该使用str.startswith,而不是索引零值,因为它更具可读性。
t.startswith('#')您应该使用字符串格式。这样可以更容易地将值插入字符串中,如下所示:
str(x + 1) + ' of ' + str(fp) + ' collected!!'可以转化为:
'{} of {} collected!!'.format(x + 1, fp)它会自动将参数转换为字符串,然后将它们放置在字符串文本中{}的位置。
https://codereview.stackexchange.com/questions/107834
复制相似问题