它不是大部分pythonic答案,但我会把它放在这里为乐趣,因为这是一个递归的教训
def find_files(files, dirs=[], extensions=[]):
new_dirs = []
for d in dirs:
try:
new_dirs += [ os.path.join(d, f) for f in os.listdir(d) ]
except OSError:
if os.path.splitext(d)[1] in extensions:
files.append(d)
if new_dirs:
find_files(files, new_dirs, extensions)
else:
return
在我的机器我有两个文件夹,root
和root2
[email protected] ]ls -R root root2
root:
temp1 temp2
root/temp1:
temp1.1 temp1.2
root/temp1/temp1.1:
f1.mid
root/temp1/temp1.2:
f.mi f.mid
root/temp2:
tmp.mid
root2:
dummie.txt temp3
root2/temp3:
song.mid
可以说,我想找到任何这些目录中的所有.txt
和所有.mid
文件,然后我可以做
files = []
find_files(files, dirs=['root','root2'], extensions=['.mid','.txt'])
print(files)
#['root2/dummie.txt',
# 'root/temp2/tmp.mid',
# 'root2/temp3/song.mid',
# 'root/temp1/temp1.1/f1.mid',
# 'root/temp1/temp1.2/f.mid']
如果它不是一个列表理解,这将更具可读性...... –