如何使用glob.glob模块搜索子文件夹?

编程入门 行业动态 更新时间:2024-10-25 20:28:10
本文介绍了如何使用glob.glob模块搜索子文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在一个文件夹中打开一系列子文件夹,找到一些文本文件并打印一些文本文件行.我正在使用这个:

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模块搜索子文件夹?

本文发布于:2023-10-07 14:41:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469663.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   文件夹   模块   glob

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!