这是我所拥有的:

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是一个简单的改编(只在执行过程中产生中间结果,而不是扩展一个结果列表到最后返回)。

其他回答

下面是我的解决方案,使用列表理解在一个目录和所有子目录中递归地搜索多个文件扩展名:

import os, glob

def _globrec(path, *exts):
""" Glob recursively a directory and all subdirectories for multiple file extensions 
    Note: Glob is case-insensitive, i. e. for '\*.jpg' you will get files ending
    with .jpg and .JPG

    Parameters
    ----------
    path : str
        A directory name
    exts : tuple
        File extensions to glob for

    Returns
    -------
    files : list
        list of files matching extensions in exts in path and subfolders

    """
    dirs = [a[0] for a in os.walk(path)]
    f_filter = [d+e for d in dirs for e in exts]    
    return [f for files in [glob.iglob(files) for files in f_filter] for f in files]

my_pictures = _globrec(r'C:\Temp', '\*.jpg','\*.bmp','\*.png','\*.gif')
for f in my_pictures:
    print f

这是Python 2.7上的一个工作代码。作为devops工作的一部分,我被要求编写一个脚本来移动标有live-appName的配置文件。属性到appName.properties。可能还有其他扩展文件,比如live-appName.xml。

下面是一个工作代码,它查找给定目录中的文件(嵌套级别),然后将其重命名(移动)到所需的文件名

def flipProperties(searchDir):
   print "Flipping properties to point to live DB"
   for root, dirnames, filenames in os.walk(searchDir):
      for filename in fnmatch.filter(filenames, 'live-*.*'):
        targetFileName = os.path.join(root, filename.split("live-")[1])
        print "File "+ os.path.join(root, filename) + "will be moved to " + targetFileName
        shutil.move(os.path.join(root, filename), targetFileName)

此函数从主脚本调用

flipProperties(searchDir)

希望这能帮助有类似问题的人。

Johan和Bruno就上述最低要求提供了出色的解决方案。我刚刚发布了Formic,它实现了Ant FileSet和glob,可以处理这种情况和更复杂的场景。您的需求的实现是:

import formic
fileset = formic.FileSet(include="/src/**/*.c")
for file_name in fileset.qualified_files():
    print file_name
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是一个简单的改编(只在执行过程中产生中间结果,而不是扩展一个结果列表到最后返回)。

如果这可能会引起任何人的兴趣,我已经介绍了前三种建议的方法。 我在globbed文件夹中有大约500K个文件(总共),并且有2K个文件符合所需的模式。

下面是(非常基本的)代码

import glob
import json
import fnmatch
import os
from pathlib import Path
from time import time


def find_files_iglob():
    return glob.iglob("./data/**/data.json", recursive=True)


def find_files_oswalk():
    for root, dirnames, filenames in os.walk('data'):
        for filename in fnmatch.filter(filenames, 'data.json'):
            yield os.path.join(root, filename)

def find_files_rglob():
    return Path('data').rglob('data.json')

t0 = time()
for f in find_files_oswalk(): pass    
t1 = time()
for f in find_files_rglob(): pass
t2 = time()
for f in find_files_iglob(): pass 
t3 = time()
print(t1-t0, t2-t1, t3-t2)

我得到的结果是: os_walk: ~ 3.6秒 rglob ~ 14.5秒 iglob: ~ 16.9秒

平台:Ubuntu 16.04, x86_64(核心i7),