首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >m3u文件收集器

m3u文件收集器
EN

Code Review用户
提问于 2015-10-16 23:22:53
回答 1查看 945关注 0票数 5

我是Python新手,编写了这段代码,用于收集m3u (播放列表)文件中的所有文件,并将它们复制到目录中。

代码语言:javascript
复制
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!"
EN

回答 1

Code Review用户

发布于 2015-10-19 10:24:18

不要使用os.path.exists(dest) != True,只需使用if not os.path.exists(dest)。一般来说,测试布尔人就像这样,而不是对它们使用等价。

x = x + 1可以很容易地重写为x += 1

您还应该使用str.startswith,而不是索引零值,因为它更具可读性。

代码语言:javascript
复制
t.startswith('#')

您应该使用字符串格式。这样可以更容易地将值插入字符串中,如下所示:

代码语言:javascript
复制
str(x + 1) + ' of ' + str(fp) + ' collected!!'

可以转化为:

代码语言:javascript
复制
'{} of {} collected!!'.format(x + 1, fp)

它会自动将参数转换为字符串,然后将它们放置在字符串文本中{}的位置。

票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/107834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档