0

我想递归地在文件夹中搜索包含文件名“x.txt”和“y.txt”的文件夹。例如,如果它是 given /path/to/folder/path/to/folder/one/two/three/four/x.txt并且/path/to/folder/one/two/three/four/y.txt存在,它应该返回一个包含 item 的列表"/path/fo/folder/one/two/three/four"。如果给定文件夹中的多个文件夹满足条件,则应将它们全部列出。这可以通过一个简单的循环来完成,还是更复杂?

4

1 回答 1

2

os.walk为您完成递归迭代目录结构的艰苦工作:

import os

find = ['x.txt', 'y.txt']

found_dirs = []
for root, dirs, files in os.walk('/path/to/folder'):
    if any(filename in files for filename in find):
        found_dirs.append(root)

#found_dirs now contains all of the directories which matched
于 2013-01-05T16:05:38.687 回答