欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

浅析python标准库中的glob

时间:2021-02-07 14:50:16|栏目:Python代码|点击:

 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导入pandas具体步骤方法

栏    目:Python代码

下一篇:使用pyecharts1.7进行简单的可视化大全

本文标题:浅析python标准库中的glob

本文地址:http://www.codeinn.net/misctech/58799.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有