浅析python标准库中的glob

发布时间:2020-09-22 23:26:10 作者:luminousjj
来源:脚本之家 阅读:115

 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、单个字符通配符

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

import glob

for name in glob.glob('dir/file?.txt'):
  print (name)

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

3、字符范围

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

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']

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

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

总结

到此这篇关于浅析python标准库中的glob的文章就介绍到这了,更多相关python标准库 glob内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!

推荐阅读:
  1. 什么是python标准库
  2. Python标准库都有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 标准库 glob

上一篇:java以json格式向后台服务器接口发送请求的实例

下一篇:flutter编写精美的登录页面

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》