当前位置:
首页 > Python基础教程 >
-
python用glob模块匹配路径的方法详解
glob模块是Python的一个标准库,用于在文件系统中查找文件名匹配特定模式的文件路径。
可以使用glob模块进行文件系统的通配符匹配,类似于在命令行中使用*和?通配符进行文件查找。
glob
glob可以通过通配符查找路径。例如
>>> import glob
>>> for i in range(10):
... temp = open(str(i)+'.py','w')
... temp.close()
...
>>> glob.glob(r'E:\Documents\00\1101\*.py')
返回值如下
[‘E:\Documents\00\1101\0.py’, ‘E:\Documents\00\1101\1.py’, ‘E:\Documents\00\1101\2.py’, ‘E:\Documents\00\1101\3.py’, ‘E:\Documents\00\1101\4.py’, ‘E:\Documents\00\1101\5.py’, ‘E:\Documents\00\1101\6.py’, ‘E:\Documents\00\1101\7.py’, ‘E:\Documents\00\1101\8.py’, ‘E:\Documents\00\1101\9.py’]
查看源码可以发现,glob是通过list(iglob(**))实现的,iglob返回一个符合要求路径的迭代器,glob将其转化为列表。
>>> it = glob.iglob(r'E:\Documents\00\1101\*.py')
>>> next(it)
'E:\\Documents\\00\\1101\\0.py'
>>> next(it)
'E:\\Documents\\00\\1101\\1.py'
>>> next(it)
'E:\\Documents\\00\\1101\\2.py'
>>> list(it)
['E:\\Documents\\00\\1101\\3.py', 'E:\\Documents\\00\\1101\\4.py', 'E:\\Documents\\00\\1101\\5.py', 'E:\\Documents\\00\\1101\\6.py', 'E:\\Documents\\00\\1101\\7.py', 'E:\\Documents\\00\\1101\\8.py', 'E:\\Documents\\00\\1101\\9.py']
fnmatch
除了*可以被转义之外,glob还可以将[]?等字符进行转义,其方法结合了os.scandir()和fnmatch.fnmatch()函数,例如
>>> glob.glob(r'E:\Documents\00\1101\[1-5].py')
[‘E:\Documents\00\1101\1.py’, ‘E:\Documents\00\1101\2.py’, ‘E:\Documents\00\1101\3.py’, ‘E:\Documents\00\1101\4.py’, ‘E:\Documents\00\1101\5.py’]
fnmatch是python中的文件夹匹配模块,其匹配规则为
模式 | * | ? | [seq] | [!seq] |
---|---|---|---|---|
含意 | 所有字符 | 任何单个字符 | seq中任何字符 | 不在seq中的字符 |
fnmatch中封装了一个正则表达式转化函数,可将fnmatch的匹配规则转为正则表达式的匹配规则,例如 |
>>> fnmatch.translate('[1-5]*.py')
'(?s:[1-5].*\\.py)\\Z'
到此这篇关于python用glob模块匹配路径的方法详解的文章就介绍到这了,更多相关python glob匹配路径内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://tinycool.blog.csdn.net/article/details/121074184
栏目列表
最新更新
求1000阶乘的结果末尾有多少个0
详解MyBatis延迟加载是如何实现的
IDEA 控制台中文乱码4种解决方案
SpringBoot中版本兼容性处理的实现示例
Spring的IOC解决程序耦合的实现
详解Spring多数据源如何切换
Java报错:UnsupportedOperationException in Col
使用Spring Batch实现批处理任务的详细教程
java中怎么将多个音频文件拼接合成一个
SpringBoot整合ES多个精确值查询 terms功能实
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
开启SQLSERVER数据库缓存依赖优化网站性能
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比