Python 删除特定文件扩展名

7 投票
2 回答
15588 浏览
提问于 2025-04-17 04:41

我刚接触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 个回答

2

如果这个程序能正常运行,而且速度也可以,那我就不打算改动它。

否则,你可以试试unutbu的回答。

一般来说,我会省略掉

png = "png"
jpg = "jpg"

这些东西,因为我觉得直接使用字符串更方便。

而且最好检查一下是否是“.png”而不是“png”。

一个更好的办法是把

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

定义在一个中心位置,然后在

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

中使用它。

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))

撰写回答