2014-03-03 104 views
2

我已經運行下面的代碼剛剛搜索當前文件夾遞歸發現

for file in os.listdir("/folder/test"): 
    if fnmatch.fnmatch(file, 'text*'): 
     print file 

如何搜索所有子文件夾以及在Python文件?

+2

檢查['os.walk'(HTTP://docs.python。組織/ 2 /庫/ os.html#os.walk) – thefourtheye

回答

3

您可以使用這樣

for dirpath, dirnames, filenames in os.walk("/folder/test"): 
    for file in filenames: 
     if fnmatch.fnmatch(file, 'text*'): 
      print file 

如果你只是想獲得的所有文件,

from os import walk, path 
from fnmatch import fnmatch 
[path.join(dpath, file) for dpath, _, files in os.walk("/folder/test") for file in files if fnmatch(file, 'text*')]