浅析python标准库中的glob

(编辑:jimmy 日期: 2024/9/23 浏览:2)

 glob 文件名模式匹配,不用遍历整个目录判断每个文件是不是符合。

1、通配符

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

import glob
for name in glob.glob('dir/*'):
  print (name)

dir/file.txt
dir/file1.txt
dir/file2.txt
dir/filea.txt
dir/fileb.txt
dir/subdir

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

import glob

#用子目录查询文件
print ('Named explicitly:')
for name in glob.glob('dir/subdir/*'):
  print ('\t', name)
#用通配符* 代替子目录名
print ('Named with wildcard:')
for name in glob.glob('dir/*/*'):
  print ('\t', name)

Named explicitly:
    dir/subdir/subfile.txt
Named with wildcard:
    dir/subdir/subfile.txt

2、单个字符通配符

用问号("htmlcode">

import glob

for name in glob.glob('dir/file"htmlcode">
import glob
for name in glob.glob('dir/*[0-9].*'):
  print (name)

dir/file1.txt
dir/file2.txt

知识点补充:Python编程:glob模块进行文件名模式匹配

文件准备

$ mkdir tmp
$ cd tmp
$ touch file1.txt
$ touch file2.txt
$ touch file3.log
$ ls
file1.txt       file2.txt       file3.log

测试

import glob

# 使用零个或多个字符通配符 * 
glob.glob("tmp/*.txt")
Out[1]: 
['file1.txt', 'file2.txt']

# 使用单字符通配符 "tmp/file")
Out[2]: 
['file1.txt', 'file2.txt']

# 使用范围匹配
glob.glob("tmp/file[0-9].txt")
Out[3]: 
['file1.txt', 'file2.txt']

总结