问题描述
我想在一个文件夹中打开一系列子文件夹,找到一些文本文件并打印一些文本文件行.我正在使用这个:
I want to open a series of subfolders in a folder and find some text files and print some lines of the text files. I am using this:
configfiles = glob.glob('C:/Users/sam/Desktop/file1/*.txt')
但是,这也无法访问子文件夹.有谁知道我也可以使用相同的命令来访问子文件夹?
But this cannot access the subfolders as well. Does anyone know how I can use the same command to access subfolders as well?
推荐答案
在Python 3.5及更高版本中,使用新的递归**/
功能:
In Python 3.5 and newer use the new recursive **/
functionality:
configfiles = glob.glob('C:/Users/sam/Desktop/file1/**/*.txt', recursive=True)
设置recursive
时,**
后跟路径分隔符将匹配0个或多个子目录.
When recursive
is set, **
followed by a path separator matches 0 or more subdirectories.
在早期的Python版本中,glob.glob()
无法递归列出子目录中的文件.
In earlier Python versions, glob.glob()
cannot list files in subdirectories recursively.
在这种情况下,我将使用 os.walk()
与 fnmatch.filter()
组合:
In that case I'd use os.walk()
combined with fnmatch.filter()
instead:
import os
import fnmatch
path = 'C:/Users/sam/Desktop/file1'
configfiles = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(path)
for f in fnmatch.filter(files, '*.txt')]
这将递归遍历您的目录,并将所有绝对路径名返回到匹配的.txt
文件.在这种特定情况下,fnmatch.filter()
可能会过大,您也可以使用.endswith()
测试:
This'll walk your directories recursively and return all absolute pathnames to matching .txt
files. In this specific case the fnmatch.filter()
may be overkill, you could also use a .endswith()
test:
import os
path = 'C:/Users/sam/Desktop/file1'
configfiles = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(path)
for f in files if f.endswith('.txt')]
这篇关于如何使用glob.glob模块搜索子文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!