【发布时间】:2019-04-14 12:07:46
【问题描述】:
路径中的任何双星号表示所有sub-directories。
现在,如果我有这样的路径 a/b/c/**/*.txt 这意味着我需要 c 下所有子目录下的所有文件。如何在 python 中得到它?
【问题讨论】:
标签: python-3.x path wildcard
路径中的任何双星号表示所有sub-directories。
现在,如果我有这样的路径 a/b/c/**/*.txt 这意味着我需要 c 下所有子目录下的所有文件。如何在 python 中得到它?
【问题讨论】:
标签: python-3.x path wildcard
让我们考虑一个例子。 考虑包含以下文件的目录:1.gif、2.txt、card.gif 和仅包含文件 3.txt 的子目录 sub。
更新:
pathlib 现在为最常见的路径操作提供了一个令人惊叹的界面。此任务也可以通过 pathlib 完成,如下所示:
from pathlib import Path
path = Path(r".") # path to the root dir from where you want to start searching
list(path.glob("**/*.txt"))
Out[1]: [WindowsPath('2.txt'), WindowsPath('sub/3.txt')]
较早的答案见下文
使用glob.
来自文档:
glob() 将产生以下结果。请注意路径的任何前导组件是如何保留的。
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True) #python 3.5+
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']
对于python
对于较旧的 Python 版本,使用 os.walk 递归遍历目录并使用 fnmatch.filter 匹配简单表达式:
import fnmatch
import os
matches = []
for root, dirnames, filenames in os.walk('src'):
for filename in fnmatch.filter(filenames, '*.txt'):
matches.append(os.path.join(root, filename))
【讨论】:
recursive 不是论据。 2)如果我做./**/*,它只会进入单个子目录,而我需要遍历所有子目录(多级)。