glob介绍
glob是python自带的一个操作文件的相关模块。用它可以查找符合特定规则的文件路径名。使用该模块查找文件,只需要用到: “*”, “?”, “[]”, “**”这四个匹配符;
* : 匹配所有字符
? : 匹配一个字符
[] : 匹配指定范围内的字符,如[0-9]匹配数字。
** : 匹配所有文件、目录、子目录和子目录里的文件(需配合其他参数)
下面实例的目录结构
glob.glob
函数分析
glob.glob(pathname, *, recursive=False)
pathname : 要匹配的文件名称
* :非参数,只是限定符
recursive : If recursive is true, the pattern '**' will match any files and zero or more directories and subdirectories. 默认为False
如果有匹配,glob.glob(path)的结果放入一个列表中返回
如果没有匹配的,glob.glob(path)将返回一个空的list:[]
实例验证
- 对于recursive和**的实例验证
res = glob.glob(’.\imgs\**’, recursive=False)
print(res)
[’.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’, ‘.\imgs\one_dir’]
res = glob.glob(’.\imgs\**’, recursive=True)
print(res)
[’.\imgs\’, ‘.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’, ‘.\imgs\one_dir’, ‘.\imgs\one_dir\one_file.py’, ‘.\imgs\one_dir\one_file.txt’]
当**匹配符遇到recursive=True,擦出了不一样的火花
- 对于*号的实例验证
-
匹配imgs路径下的所有文件/路径
res = glob.glob(’.\imgs\*’, recursive=True)
print(res)
[’.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’, ‘.\imgs\one_dir’]
res = glob.glob(’.\imgs\*’, recursive=False)
print(res)
[’.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’, ‘.\imgs\one_dir’]
recursive无论为True还是False 对于*匹配符都是没有影响的。 -
只匹配目录下的所有文件,不再匹配目录下的目录
res = glob.glob(’.\imgs\*.*’)
print(res)
[’.\imgs\cat.png’, ‘.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’]
-
过滤出所有txt文件
res = glob.glob(’.\imgs\*.txt’, recursive=False)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’] -
匹配当前路径下面的路径下的所有png图片
res = glob.glob(’.\*\*.png’)
print(res)
[’.\imgs\cat.png’]
- 对于?号的使用
-
只匹配hello0.txt到hello9.txt
res = glob.glob(’.\imgs\hello?.txt’)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello2.txt’] -
获取目录下文件名为6个字符的文件
res = glob.glob(’.\imgs\??????.*’)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello2.txt’]
- 对于[]号的使用
-
只匹配hello0.txt到hello9.txt
res = glob.glob(’.\imgs\hello[0-9].txt’)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello2.txt’] -
匹配imgs目录下包含数字的文件
res = glob.glob(’.\imgs\*[0-9]*.*’)
print(res)
[’.\imgs\hello0.txt’, ‘.\imgs\hello100.txt’, ‘.\imgs\hello2.txt’]
- 匹配以.开头的文件或路径
glob函数默认不搜索以.点号开头的文件和路径,如果要求的话需要单独写个点号.
res = glob.glob(’.\imgs\.*.*’)
print(res)
[’.\imgs\.pip.config’]
glob.iglob函数分析
iglob(pathname, *, recursive=False)
iglob和glob.glob的用法一样。区别就在于它返回的是一个生成器。
res = glob.iglob(’.\imgs\*[0-9]*.*’)
print(res)
<generator object _iglob at 0x000001F508DA4678>
for r in res:
print(r)
.\imgs\hello0.txt
.\imgs\hello100.txt
.\imgs\hello2.txt
glob.escape函数分析
escape(pathname)
输入路径名称,转义所有特殊字符
它返回的是一个glob规则,将 *,?,[] 这三个特殊符号转换成可以去匹配含有这三个特殊符号字符串的glob规则
res = glob.escape(’.\imgs\*.txt’)
print(res)
.\imgs[*].txt