标准库之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介绍
发布评论