脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python: glob匹配文件的操作

Python: glob匹配文件的操作

2021-08-12 00:49米乐乐果- Python

这篇文章主要介绍了Python: glob匹配文件的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

glob模块实例详解

glob的应用场景是要寻找一系列(符合特定规则)文件名。

glob模块是最简单的模块之一,内容非常少。用它可以查找符合特定规则的文件路径名。查找文件只用到三个匹配符:”*”, “?”, “[]”。

”*”匹配0个或多个字符;

”?”匹配单个字符;

”[ ]”匹配指定范围内的字符,如:[0-9]匹配数字。

假设以下例子目录是这样的。

?
1
2
3
4
5
6
7
8
dir
dir/file.txt
dir/file1.txt
dir/file2.txt
dir/filea.txt
dir/fileb.txt
dir/subdir
dir/subdir/subfile.txt

匹配所有文件

可以用*匹配任意长度字节。glob.glob比较常用,返回一个list,也可用glob.iglob返回生成器。

?
1
2
3
import glob
for name in glob.glob('dir/*'):
  print name
?
1
2
3
4
5
6
dir/file.txt
dir/file1.txt
dir/file2.txt
dir/filea.txt
dir/fileb.txt
dir/subdir

匹配子目录文件

可以指定子目录名称,也可以用通配符代替,不显示指定。

?
1
2
3
4
5
6
7
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
?
1
2
3
4
Named explicitly:
  dir/subdir/subfile.txt
Named with wildcard:
  dir/subdir/subfile.txt

单字节通配符匹配

除了*以外,还有?匹配单个字符。比如下面这个例子,匹配以file开头,以.txt结尾,中间是任一字符的文件。

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

print name

?
1
2
3
4
dir/file1.txt
dir/file2.txt
dir/filea.txt
dir/fileb.txt

字符区间匹配[0-9]

比如匹配后缀前是数字的文件。

for name in glob.glob('dir/*[0-9].*'):

print name

dir/file1.txt

dir/file2.txt

Ref:

官方文档

Python Module of the Week

补充知识:Python glob 递归遍历匹配文件;os.makedirs()递归创建目录

Glob递归遍历匹配文件

简约版

在python中,glob模块用来查找匹配文件

常用的匹配规则:

: 匹配所所有

? : 匹配一个字符

如果没有匹配的,glob.glob(path)将返回一个空的list:[]

?
1
2
3
from glob import glob
file_path = "/home/lihuiyu/Code/results_S2_W20040/*/*.pth"
print(glob(file_path))

排序版

我喜欢偷懒,所以,Coding能解决的问题一般不会人工解决;

我喜欢整洁,所以,Coding苛求完美,结果奢求整齐划一。

?
1
2
3
4
5
6
7
8
9
10
11
12
import re
from glob import glob
def atoi(s):
 return int(s) if s.isdigit() else s
def natural_keys(text):
 return [atoi(c) for c in re.split('(\d+)', text)]
 
file_path = "/home/lihuiyu/Code/results_S2_W20040/*/*.pth"
file_list = glob(file_path)
file_list.sort(key=natural_keys)
for name in file_list:
  print(name)

os.makedirs()递归创建目录

os.mkdir()创建指定的目录,但如果其上一级目录不存在,则无法创建成功。

os.makedirs()实现递归创建目录的功能。

以上这篇Python: glob匹配文件的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u010967162/article/details/52298188

延伸 · 阅读

精彩推荐