Python Deleting Certain File Extensions

孤人 提交于 2019-11-30 10:01:29

Since you are recursing through subdirectories, use 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))

If the program works and the speed is acceptable, I wouldn't change it.

Otherwise, you could try unutbu's answer.

Generally, I would leave away the

png = "png"
jpg = "jpg"

stuff as I don't see any purpose in not using the strings directly.

And better test for ".png" instead of "png".

An even better solution would be to define

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

somewhere centally and use that in

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

.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!