Python删除某些文件扩展名

时间:2011-10-20 09:21:21

标签: python logic file-extension delete-file

我对Python很陌生,但是我已经让这段代码工作了,事实上,做了它想做的事。

但是,我想知道是否有更有效的方法对此进行编码,或许是为了提高处理速度。

 import os, glob


def scandirs(path):
    for currentFile in glob.glob( os.path.join(path, '*') ):
        if os.path.isdir(currentFile):
            print 'got a directory: ' + currentFile
            scandirs(currentFile)
        print "processing file: " + currentFile
        png = "png";
        jpg = "jpg";
        if currentFile.endswith(png) or currentFile.endswith(jpg):
            os.remove(currentFile)

scandirs('C:\Program Files (x86)\music\Songs')

现在,大约有8000个文件,处理每个文件并检查它是否确实以png或jpg结尾需要相当长的时间。

2 个答案:

答案 0 :(得分:15)

由于您要通过子目录进行递归,请使用os.walk

import os

def scandirs(path):
    for root, dirs, files in os.walk(path):
        for currentFile in files:
            print "processing file: " + currentFile
            exts = ('.png', '.jpg')
            if currentFile.lower().endswith(exts):
                os.remove(os.path.join(root, currentFile))

答案 1 :(得分:1)

如果程序运行且速度可以接受,我不会改变它。

否则,您可以尝试unutbu的答案。

一般来说,我会放弃

png = "png"
jpg = "jpg"

因为我没有看到任何直接使用字符串的目的。

更好地测试“.png”而不是“png”。

更好的解决方案是定义

extensions = ('.png', '.jpg')

在某个地方,在

中使用它
if any(currentFile.endswith(ext) for ext in extensions):
    os.remove(currentFile)