Python删除特定文件扩展名

7

虽然我对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结尾。


1
你可能想要查看os.path.walk - Daniel Roseman
谢谢!我会用到它的。 - Two
2个回答

20

由于您正在遍历子文件夹,因此请使用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))

如果你将 exts=('.png', '.jpg') 改为 exts=['.png', '.jpg'],那么代码也可以仅适用于一个扩展名。 - AliBZ
我原以为在最后执行第三个循环比使用os.path.splitext()方法并进行比较要慢,但是我测试了一下,这是最快的解决方案。 - Blairg23
现在你可以使用currentFile.endswith(exts)了(endswith接受一个元组)。 - Jean-François Fabre
@Jean-FrançoisFabre:感谢您的改进。 - unutbu

2
如果程序运行良好且速度可接受,我不会对其进行更改。
否则,您可以尝试unutbu的答案。
通常情况下,我会省略掉。
png = "png"
jpg = "jpg"

我认为直接使用字符串是没有问题的,因此我不认为有必要进行更改。

判断文件类型时最好使用".png"而不是"png"。

甚至更好的解决方案是定义:

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

在中心位置某处使用它,并将其用于

if any(currentFile.endswith(ext) for ext in extensions):
    os.remove(currentFile)

.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接