Python: glob匹配文件的操作

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python: glob匹配文件的操作

米乐乐果-   2020-12-11 我要评论

glob模块实例详解

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

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

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

”?”匹配单个字符;

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

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

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返回生成器。

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

匹配子目录文件

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

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

单字节通配符匹配

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

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

print name

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:[]

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

排序版

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

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

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匹配文件的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们