2013-01-05 176 views
0

我想遞歸搜索包含文件名「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/fo/folder/one/two/three/four"的列表。如果給定文件夾中的多個文件夾滿足條件,則應將其全部列出。這可以通過一個簡單的循環來完成,還是更復雜?搜索目錄中包含特定文件的目錄?

+0

這可以用一個遞歸函數來完成 –

回答

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 
相關問題