在python中递归查找文件

时间:2014-03-03 05:32:14

标签: python file python-2.7

我运行了以下代码,只搜索当前文件夹

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

如何搜索所有子文件夹?

1 个答案:

答案 0 :(得分:3)

您可以像这样使用os.walk

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*')]