Python 在目录中搜索包含特定文件的目录?

Python 在目录中搜索包含特定文件的目录?,python,Python,我想递归搜索一个文件夹,查找包含文件名“x.txt”和“y.txt”的文件夹。例如,如果给定了/path/to/folder、和/path/to/folder/one/two/three/four/x.txt和/path/to/folder/one/two/three/four/y.txt存在,它应该返回一个列表,其中包含“/path/folder/one/two/three/three/folder”。如果给定文件夹中的多个文件夹满足条件,则应列出所有文件夹。这可以通过一个简单的循环来完成,还

我想递归搜索一个文件夹,查找包含文件名“x.txt”和“y.txt”的文件夹。例如,如果给定了
/path/to/folder
、和
/path/to/folder/one/two/three/four/x.txt
/path/to/folder/one/two/three/four/y.txt
存在,它应该返回一个列表,其中包含
“/path/folder/one/two/three/three/folder”
。如果给定文件夹中的多个文件夹满足条件,则应列出所有文件夹。这可以通过一个简单的循环来完成,还是更复杂?

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

这可以通过递归函数实现