这是我所拥有的:

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, 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)

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

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

for each in glob.glob('path/**/*.c', recursive=True):
    print(f'Name with path: {each} \nName without path: {os.path.basename(each)}')

Glob.glob ('*.c'):匹配当前目录下所有以.c结尾的文件 Glob.glob ('*/*.c'):与1相同 Glob.glob ('**/*.c'):只匹配直接子目录中以.c结尾的所有文件,不匹配当前目录 glob.glob('*.c',recursive=True):与1相同 glob.glob('*/*.c',recursive=True):与3相同 glob.glob('**/*.c',recursive=True):匹配当前目录和所有子目录中以.c结尾的所有文件

如果文件位于远程文件系统上或归档文件中,则可以使用fspecabstractfilesystem类的实现。例如,要列出一个zipfile中的所有文件:

from fsspec.implementations.zip import ZipFileSystem
fs = ZipFileSystem("/tmp/test.zip")
fs.glob("/**")  # equivalent: fs.find("/")

或者列出公共S3桶中的所有文件:

from s3fs import S3FileSystem
fs_s3 = S3FileSystem(anon=True)
fs_s3.glob("noaa-goes16/ABI-L1b-RadF/2020/045/**")  # or use fs_s3.find

你也可以将它用于本地文件系统,如果你的实现应该是文件系统不可知的,这可能会很有趣:

from fsspec.implementations.local import LocalFileSystem
fs = LocalFileSystem()
fs.glob("/tmp/test/**")

其他实现包括谷歌云,Github, SFTP/SSH, Dropbox和Azure。具体操作请参见fspec API文档。

另一种方法是只使用glob模块。只需给rglob方法添加一个起始基本目录和一个要匹配的模式,它就会返回一个匹配文件名的列表。

import glob
import os

def _getDirs(base):
    return [x for x in glob.iglob(os.path.join( base, '*')) if os.path.isdir(x) ]

def rglob(base, pattern):
    list = []
    list.extend(glob.glob(os.path.join(base,pattern)))
    dirs = _getDirs(base)
    if len(dirs):
        for d in dirs:
            list.extend(rglob(os.path.join(base,d), pattern))
    return list