浅析python标准库中的glob

作者:luminousjj 时间:2023-08-04 02:39:10 

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

来源:https://www.cnblogs.com/luminousjj/p/9359543.html

标签:python,标准库,glob
0
投稿

猜你喜欢

  • 详解js加减乘除精确计算

    2024-04-18 10:47:10
  • node.js实现BigPipe详解

    2024-05-05 09:22:17
  • 解决MSSQL2005远程连接sql2000非默认端口数据库的问题

    2024-01-28 09:41:10
  • python 获取计算机的网卡信息

    2023-08-11 21:12:06
  • Python配置文件yaml的用法详解

    2023-07-04 21:02:56
  • Go语言基础for循环语句的用法及示例详解

    2024-02-07 16:15:34
  • python通过加号运算符操作列表的方法

    2023-11-12 13:44:04
  • Python并行分布式框架Celery详解

    2023-06-23 10:05:21
  • python隐藏终端执行cmd命令的方法

    2022-01-09 05:19:37
  • PHP程序员玩转Linux系列 nginx初学者引导

    2023-11-21 19:51:16
  • Javascript实现信息滚动效果

    2023-07-02 05:15:55
  • python 基于 tkinter 做个学生版的计算器

    2022-07-30 18:43:54
  • 详解Python中的各种函数的使用

    2022-03-23 22:09:52
  • Windows下ORACLE 10g完全卸载的方法分析

    2012-07-11 16:09:26
  • python交互式图形编程实例(三)

    2021-10-10 17:34:39
  • python读取hdfs并返回dataframe教程

    2022-03-22 17:15:33
  • 解决Python spyder显示不全df列和行的问题

    2021-06-23 00:15:47
  • python 七种邮件内容发送方法实例

    2022-01-13 21:06:38
  • Go语言正则表达式示例

    2023-04-13 19:41:34
  • 在Python的Flask框架下收发电子邮件的教程

    2021-03-05 08:54:37
  • asp之家 网络编程 m.aspxhome.com