我对 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 结尾需要相当长的时间。
由于您是通过子目录递归,因此使用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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)