python标准库之glob介绍

编程入门 行业动态 更新时间:2024-10-07 18:20:16

python<a href=https://www.elefans.com/category/jswz/34/1770499.html style=标准库之glob介绍"/>

python标准库之glob介绍

glob 文件名模式匹配,提供了一个函数用于从目录通配符搜索中生成文件列表,不用遍历整个目录判断每个文件是不是符合。

1 、通配符

星号(*)匹配零个或多个字符

import globfor name in glob.glob('./test/*'):print(name)

执行结果:

./test/other
./test/test_3.py
./test/test_4.py
./test/test_2.py
./test/test_1.py

列出子目录中的文件,必须在模式中包括子目录名:

import glob# 用子目录查询文件
print('用子目录查询文件:')
for name in glob.glob('test/other/*'):print('\t', name)
# 用通配符* 代替子目录名
print('用通配符 * 代替子目录名:')
for name in glob.glob('test/*/*'):print('\t', name)

执行结果:

用子目录查询文件:
     ./test/other/hello.txt
用通配符 * 代替子目录名:
     ./test/other/hello.txt

2、单个字符通配符

用问号(?)匹配任何单个的字符。

import globfor name in glob.glob('./test/test_?.py'):print(name)

执行结果:

./test/test_3.py
./test/test_4.py
./test/test_2.py
./test/test_1.py

3、字符范围

当需要匹配一个特定的字符,可以使用一个范围

import globfor name in glob.glob('test/test_[0-9].*'):print(name)

执行结果:

./test/test_3.py
./test/test_4.py
./test/test_2.py
./test/test_1.py

 

 

 

 

 

 

 

 

 

 

 

更多推荐

python标准库之glob介绍

本文发布于:2024-02-25 06:19:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1698079.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标准   python   glob

发布评论

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

>www.elefans.com

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