如何从目录树中递归收集符合条件的所有目录(例如“包含名为foo.txt的文件”)?类似的东西:
def has_my_file(d):
return ('foo.txt' in os.listdir(d))
walk_tree(dirname, criterion=has_my_file)
树的:
home/
bob/
foo.txt
sally/
mike/
foo.txt
walk_tree
应该返回:
['home/bob/', 'home/sally/mike']
在python库中有这样的功能吗?
答案 0 :(得分:2)
使用os.walk
:
import os
result = []
for parent, ds, fs in os.walk(dirname):
if 'foo.txt' in fs:
result.append(parent)
使用列表理解:
result = [parent for parent, ds, fs in os.walk(dirname) if 'foo.txt' in fs]