python 的标准库模块glob使用教程,主要为glob.glob函数使用与glob.iglob函数使用

文章目录:

  • 1 glob模块介绍
  • 2 glob模块的具体使用
    • 2.1 查看glob模块有哪些方法属性
    • 2.2 glob.glob(pathname, *, recursive=False)函数的使用
      • 2.2.1 函数glob.glob()定义:
      • 2.2.2 glob.glob()函数的参数和返回值
      • 2.2.3 glob.glob()函数使用实例
    • 2.3 glob.iglob(pathname, recursive=False)函数的使用
      • 2.3.1 glob.iglob()函数的定义
      • 2.3.2 glob.iglob()函数的参数
      • 2.3.3 glob.iglob()函数的使用实例
    • 2.4 其他通配符`*、?、[]`实例

1 glob模块介绍

glob是python的标准库模块,只要安装python就可以使用该模块。glob模块主要用来查找目录文件,可以使用*、?、[]这三种通配符对路径中的文件进行匹配。

  • *:代表0个或多个字符
  • ?:代表一个字符
  • []:匹配指定范围内的字符,如[0-9]匹配数字

Unix样式路径名模式扩展

  • glob模块英文文档:https://docs.python.org/3/library/glob.html

2 glob模块的具体使用

2.1 查看glob模块有哪些方法属性

>>> dir(glob)
['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', '_glob0', '_glob1', '_glob2', '_iglob',
'_ishidden', '_isrecursive', '_iterdir', '_rlistdir', 'escape', 'fnmatch',
'glob', 'glob0', 'glob1', 'has_magic', 'iglob', 'magic_check',
'magic_check_bytes', 'os', 're']
>>>

glob模块常用的两个方法有:glob.glob() 和 glob.iglob,下面详细介绍

2.2 glob.glob(pathname, *, recursive=False)函数的使用

2.2.1 函数glob.glob()定义:

def glob(pathname, *, recursive=False):"""Return a list of paths matching a pathname pattern.The pattern may contain simple shell-style wildcards a lafnmatch. However, unlike fnmatch, filenames starting with adot are special cases that are not matched by '*' and '?'patterns.If recursive is true, the pattern '**' will match any files andzero or more directories and subdirectories."""return list(iglob(pathname, recursive=recursive))def iglob(pathname, *, recursive=False):"""Return an iterator which yields the paths matching a pathname pattern.The pattern may contain simple shell-style wildcards a lafnmatch. However, unlike fnmatch, filenames starting with adot are special cases that are not matched by '*' and '?'patterns.If recursive is true, the pattern '**' will match any files andzero or more directories and subdirectories."""it = _iglob(pathname, recursive, False)if recursive and _isrecursive(pathname):s = next(it)  # skip empty stringassert not sreturn it

2.2.2 glob.glob()函数的参数和返回值

  • def glob(pathname, *, recursive=False):

    • pathname:该参数是要匹配的路径
    • recursive:如果是true就会递归的去匹配符合的文件路径,默认是False
  • 返回匹配到的路径列表

2.2.3 glob.glob()函数使用实例

先给出测试使用的目录结构:

test_dir/
├── a1.txt
├── a2.txt
├── a3.py
├── sub_dir1
│   ├── b1.txt
│   ├── b2.py
│   └── b3.py
└── sub_dir2├── c1.txt├── c2.py└── c3.txt

2、匹配'./test_dir/*路径下的所有目录和文件,并返回路径列表

>>> path_list2 = glob.glob('./test_dir/*')
>>> path_list2
['./test_dir/a3.py', './test_dir/a2.txt', './test_dir/sub_dir1', './test_dir/sub_dir2', './test_dir/a1.txt']

3、匹配./test_dir/路径下含有的所有.py文件不递归

>>> path_list3 = glob.glob('./test_dir/*.py')
>>> path_list3
['./test_dir/a3.py']
>>> path_list4 = glob.glob('./test_dir/*/*.py')
>>> path_list4
['./test_dir/sub_dir1/b2.py', './test_dir/sub_dir1/b3.py', './test_dir/sub_dir2/c2.py']

4、递归的匹配./test_dir/**路径下的所有目录和文件,并返回路径列表

>>> path_list5 = glob.glob('./test_dir/**', recursive=True)
>>> path_list5
['./test_dir/', './test_dir/a3.py', './test_dir/a2.txt', './test_dir/sub_dir1', './test_dir/sub_dir1/b2.py', './test_dir/sub_dir1/b3.py', './test_dir/sub_dir1/b1.txt', './test_dir/sub_dir2', './test_dir/sub_dir2/c3.txt', './test_dir/sub_dir2/c1.txt', './test_dir/sub_dir2/c2.py', './test_dir/a1.txt']
>>> path_list6 = glob.glob('./test_dir/**/*.py', recursive=True)
>>> path_list6
['./test_dir/a3.py', './test_dir/sub_dir1/b2.py', './test_dir/sub_dir1/b3.py', './test_dir/sub_dir2/c2.py']

注意:

如果要对某个路径下进行递归,一定要在后面加两个*

>>> path_list = glob.glob('./test_dir/', recursive=True)
>>> path_list
['./test_dir/']

2.3 glob.iglob(pathname, recursive=False)函数的使用

2.3.1 glob.iglob()函数的定义

def iglob(pathname, *, recursive=False):"""Return an iterator which yields the paths matching a pathname pattern.The pattern may contain simple shell-style wildcards a lafnmatch. However, unlike fnmatch, filenames starting with adot are special cases that are not matched by '*' and '?'patterns.If recursive is true, the pattern '**' will match any files andzero or more directories and subdirectories."""it = _iglob(pathname, recursive, False)if recursive and _isrecursive(pathname):s = next(it)  # skip empty stringassert not sreturn it

2.3.2 glob.iglob()函数的参数

  • glob.iglob参数glob.glob()一样
  • def iglob(pathname, *, recursive=False):
    • pathname:该参数是要匹配的路径
    • recursive:如果是true就会递归的去匹配符合的文件路径,默认是False
  • 返回一个迭代器,遍历该迭代器的结果与使用相同参数调用glob()的返回结果一致

2.3.3 glob.iglob()函数的使用实例

先给出测试使用的目录结构:

test_dir/
├── a1.txt
├── a2.txt
├── a3.py
├── sub_dir1
│   ├── b1.txt
│   ├── b2.py
│   └── b3.py
└── sub_dir2├── c1.txt├── c2.py└── c3.txt

正常glob.glob()返回路径列表

>>> path_list4 = glob.glob('./test_dir/*/*.py')
>>> path_list4
['./test_dir/sub_dir1/b2.py', './test_dir/sub_dir1/b3.py', './test_dir/sub_dir2/c2.py']

现在,使用:glob.iglob()

>>> file_path_iter = glob.iglob('./test_dir/*')
>>> print(type(file))
<class 'generator'>
>>> for file_path in file_path_iter:
...     print(file_path)
...
./test_dir/a3.py
./test_dir/a2.txt
./test_dir/sub_dir1
./test_dir/sub_dir2
./test_dir/a1.txt
>>>

2.4 其他通配符*、?、[]实例

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']

Python 文件(文件夹)匹配(glob模块)(转载)相关推荐

  1. devi into python 笔记(五)异常 文件操作 sys os glob模块简单实用

    异常: Java异常: try catch块处理异常,throw引发异常. Python异常: try except块处理异常,raise引发异常. 异常如果不主动处理,则会交给Python中的缺省处 ...

  2. python中glob_python中的glob模块

    简介 glob模块可以查找符合特定规则的文件路径名.跟使用windows下的文件搜索差不多.它有三个匹配符:"*", "?", "[]". ...

  3. python删除文件夹下文件夹_python删除指定文件夹下文件和文件夹的方法详解

    前记 python删除指定文件夹下的文件,是一个常用的功能.我找了不少地方,一直没有找到合适的模版,那只好自己倒腾一个比较实用的模版了. 基本模块 这里面会用到几个模块,一个是目录下所有文件的的函数: ...

  4. python 临时文件夹 的 tempfile模块学习

     python的临时文件夹的tempfile模块学习 应用程序经常要保存一些临时的信息,这些信息不是特别重要,没有必要写在配置文件 里,但又不能没有,这时候就可以把这些信息写到临时文件里.其实很 ...

  5. pythontemp_python 临时文件夹 的 tempfile模块学习

    python的临时文件夹的tempfile模块学习 应用程序经常要保存一些临时的信息,这些信息不是特别重要,没有必要写在配置文件 里,但又不能没有,这时候就可以把这些信息写到临时文件里.其实很 多程序 ...

  6. Python标准库笔记(9) — functools模块

    functools 作用于函数的函数 functools 模块提供用于调整或扩展函数和其他可调用对象的工具,而无需完全重写它们. 装饰器 partial 类是 functools 模块提供的主要工具, ...

  7. Python之glob模块进行文件匹配及遍历

    Python之glob模块进行文件匹配及遍历 glob是python自带的一个操作文件的相关模块,用来查找符合特定规则的文件路径,是python处理文件路径相关问题中常用的包. glob 文件名模式匹 ...

  8. python中glob模块怎么下_如何在Python中使用glob.glob模块搜索子文件夹?

    如何在Python中使用glob.glob模块搜索子文件夹? 我想在文件夹中打开一系列子文件夹,找到一些文本文件并打印一些文本文件行. 我用这个: configfiles = glob.glob('C ...

  9. Python学习笔记——glob模块【文件、路径操作】

    最近做了一个将dicom文件转化为mhd文件的任务,由于要进行批量转化所以遍历文件夹必不可少,刚开始学习python编程,所以把用过的模块用法记录下来,以加深记忆,方便查阅,最后参考前人的博客做了gl ...

  10. python中的glob 模块学习文件路径查找

    glob glob.glob(pathname), 返回所有匹配的文件路径列表.它只有一个参数pathname,定义了文件路径匹配规则,这里可以是绝对路径,也可以是相对路径. import glob ...

最新文章

  1. 比较高明的暗部提亮方法:选取暗部,滤色叠加
  2. node.js request get 请求怎么拿到返回的数据_NodeJS运维: 从 0 开始 Prometheus + Grafana 业务性能指标监控...
  3. 02 typedef
  4. 全美杰出的技术MBA专业
  5. django新建一个项目_如何使用Django创建项目
  6. 数据库-MySQL-JDBC框架
  7. 进程间通信 --- 命名管道 有名管道存在与内存中,无名管道存在与文件系统中 换种角度看问题
  8. 惠普打印机136w硒鼓芯片怎么清零_HP惠普打印机清零技巧
  9. 推荐几个前端模板下载站
  10. loadrunner代理录制
  11. signature=a50e5f0f4a417f58d5844d45a67fb641,angular中文转拼音工具
  12. 计算机相关设备巡检表,电脑维护巡检方案
  13. 搭建hexo个人网站小试
  14. 【论文阅读】A Survey of Incentive Mechanism Design for Federated Learning 联邦学习激励机制设计综述
  15. cbecame计算机辅助教育,电子白板辅助下英语阅读理解中长难句教学策略浅析
  16. 洛谷P2678 Java解法
  17. Spring Boot使用qq邮箱实现验证码发送
  18. 1小时1篇文学会用python进行AI修复!
  19. mysql 中继日志路径,MySQL各种日志总结
  20. RHEL7OSP-6.0的Linux底层管理

热门文章

  1. javaScript中简单数据类型和复杂数据类型赋值拷贝的理解
  2. vux和iview的弹出框总结
  3. UVA 10572 Black and White(插头DP)
  4. ComponentOne 2018V2正式发布,提供轻量级的 .NET
  5. SpringBoot(四):mybatis之通用mapper、分页插件PageHelper
  6. CentOS基本的命令与快捷建
  7. ubuntu openStack icehouse dashboard theme自定义
  8. java多线程 Java核心技术 读书笔记
  9. Access中使用SQL语句应掌握的几点技巧
  10. 6. URL (2)