如何使用glob()递归查找文件? [英] How to use glob() to find files recursively?
问题描述
这就是我所拥有的:
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.
推荐答案
Python 3.5 +
由于您使用的是新的python,因此应使用 pathlib
模块中的pathlib.Path.rglob
. >
Since you're on a new python, you should use pathlib.Path.rglob
from the the pathlib
module.
from pathlib import Path
for path in Path('src').rglob('*.c'):
print(path.name)
如果您不想使用pathlib,只需使用 recursive
关键字参数.
If you don't want to use pathlib, just use glob.glob
, but don't forget to pass in the recursive
keyword parameter.
如果匹配的文件以点(.)开头;例如当前目录中的文件或基于Unix的系统上的隐藏文件,请使用 c4> 下面的解决方案.
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.
Python的旧版本
对于较旧的Python版本,请使用 os.walk
来递归遍历目录,然后 fnmatch.filter
来匹配一个简单的目录表达式:
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屋!