glob 文件名模式匹配,提供了一个函数用于从目录通配符搜索中生成文件列表,不用遍历整个目录判断每个文件是不是符合。
1 、通配符
星号(*)匹配零个或多个字符
import glob
for 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
<