如何使用 glob() 递归查找文件? [英] How to use glob() to find files recursively?

查看:51
本文介绍了如何使用 glob() 递归查找文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我所拥有的:

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

但我想搜索 src 的子文件夹.像这样的事情会起作用:

but I want to search the subfolders of src. Something like this would work:

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

但这显然是有限且笨重的.

But this is obviously limited and clunky.

推荐答案

pathlib.Path.rglob

使用 pathlib.Path.rglob 来自 pathlib 模块,这是在 Python 3.5 中引入的.

Use pathlib.Path.rglob from the the pathlib module, which was introduced in Python 3.5.

from pathlib import Path

for path in Path('src').rglob('*.c'):
    print(path.name)

如果不想使用pathlib,可以使用glob.glob('**/*.c'),但不要忘记传入 recursive 关键字参数,它会使用过多的大目录上的时间.

If you don't want to use pathlib, use can use glob.glob('**/*.c'), but don't forget to pass in the recursive keyword parameter and it will use inordinate amount of time on large directories.

对于匹配文件以点开头的情况(.);像当前目录中的文件或基于 Unix 的系统上的隐藏文件,使用 os.walk 下面的解决方案.

For cases where matching files beginning with a dot (.); like files in the current directory or hidden files on Unix based system, use the os.walk solution below.

os.walk

对于较旧的 Python 版本,请使用 os.walk 递归遍历目录和fnmatch.过滤以匹配一个简单的表达式:

For older Python versions, use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:

import fnmatch
import os

matches = []
for root, dirnames, filenames in os.walk('src'):
    for filename in fnmatch.filter(filenames, '*.c'):
        matches.append(os.path.join(root, filename))

这篇关于如何使用 glob() 递归查找文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆