这是我所拥有的:

glob(os.path.join('src','*.c'))

但是我想搜索src的子文件夹。这样做是可行的:

glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))

但这显然是有限和笨拙的。


当前回答

import os
import fnmatch


def recursive_glob(treeroot, pattern):
    results = []
    for base, dirs, files in os.walk(treeroot):
        goodfiles = fnmatch.filter(files, pattern)
        results.extend(os.path.join(base, f) for f in goodfiles)
    return results

Fnmatch提供了与glob完全相同的模式,因此这是glob的绝佳替代品。语义非常接近的Glob。迭代版本(例如生成器),替换glob。Iglob是一个简单的改编(只在执行过程中产生中间结果,而不是扩展一个结果列表到最后返回)。

其他回答

或者使用列表推导式:

 >>> base = r"c:\User\xtofl"
 >>> binfiles = [ os.path.join(base,f) 
            for base, _, files in os.walk(root) 
            for f in files if f.endswith(".jpg") ] 

根据其他答案,这是我目前的工作实现,检索根目录中的嵌套XML文件:

files = []
for root, dirnames, filenames in os.walk(myDir):
    files.extend(glob.glob(root + "/*.xml"))

我真的很喜欢python:)

你需要使用操作系统。行走以收集符合条件的文件名。例如:

import os
cfiles = []
for root, dirs, files in os.walk('src'):
  for file in files:
    if file.endswith('.c'):
      cfiles.append(os.path.join(root, file))

我需要一个python 2的解决方案。在大目录上快速工作的X。 我得出了这个结论:

import subprocess
foundfiles= subprocess.check_output("ls src/*.c src/**/*.c", shell=True)
for foundfile in foundfiles.splitlines():
    print foundfile

注意,您可能需要一些异常处理,以防ls找不到任何匹配的文件。

从Python 3.4开始,可以在新的pathlib模块中使用Path类之一的glob()方法,它支持**通配符。例如:

from pathlib import Path

for file_path in Path('src').glob('**/*.c'):
    print(file_path) # do whatever you need with these files

更新: 从Python 3.5开始,glob.glob()也支持相同的语法。