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

简介: python 的标准库模块glob使用教程,主要为glob.glob()使用与glob.iglob()使用

1 glob模块介绍

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

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

Unix样式路径名模式扩展

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 la
    fnmatch. However, unlike fnmatch, filenames starting with a
    dot are special cases that are not matched by '*' and '?'
    patterns.

    If recursive is true, the pattern '**' will match any files and
    zero 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 la
    fnmatch. However, unlike fnmatch, filenames starting with a
    dot are special cases that are not matched by '*' and '?'
    patterns.

    If recursive is true, the pattern '**' will match any files and
    zero or more directories and subdirectories.
    """
    it = _iglob(pathname, recursive, False)
    if recursive and _isrecursive(pathname):
        s = next(it)  # skip empty string
        assert not s
    return 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

1、返回目录的路径列表

>>> path_list1 = glob.glob('./test_dir/')
>>> path_list
['./test_dir/']

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 la
    fnmatch. However, unlike fnmatch, filenames starting with a
    dot are special cases that are not matched by '*' and '?'
    patterns.

    If recursive is true, the pattern '**' will match any files and
    zero or more directories and subdirectories.
    """
    it = _iglob(pathname, recursive, False)
    if recursive and _isrecursive(pathname):
        s = next(it)  # skip empty string
        assert not s
    return 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/']
目录
相关文章
|
20天前
|
存储 人工智能 测试技术
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
本文介绍如何使用LangChain结合DeepSeek实现多轮对话,测开人员可借此自动生成测试用例,提升自动化测试效率。
221 125
如何使用LangChain的Python库结合DeepSeek进行多轮次对话?
|
13天前
|
监控 数据可视化 数据挖掘
Python Rich库使用指南:打造更美观的命令行应用
Rich库是Python的终端美化利器,支持彩色文本、智能表格、动态进度条和语法高亮,大幅提升命令行应用的可视化效果与用户体验。
62 0
|
12天前
|
安全 大数据 程序员
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
`operator.methodcaller`是Python中处理对象方法调用的高效工具,替代冗长Lambda,提升代码可读性与性能。适用于数据过滤、排序、转换等场景,支持参数传递与链式调用,是函数式编程的隐藏利器。
52 4
|
2月前
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
114 18
|
2月前
|
机器学习/深度学习 API 异构计算
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
JAX是Google开发的高性能数值计算库,旨在解决NumPy在现代计算需求下的局限性。它不仅兼容NumPy的API,还引入了自动微分、GPU/TPU加速和即时编译(JIT)等关键功能,显著提升了计算效率。JAX适用于机器学习、科学模拟等需要大规模计算和梯度优化的场景,为Python在高性能计算领域开辟了新路径。
179 0
JAX快速上手:从NumPy到GPU加速的Python高性能计算库入门教程
|
2月前
|
存储 安全 数据处理
Python 内置模块 collections 详解
`collections` 是 Python 内置模块,提供多种高效数据类型,如 `namedtuple`、`deque`、`Counter` 等,帮助开发者优化数据处理流程,提升代码可读性与性能,适用于复杂数据结构管理与高效操作场景。
103 0
|
2月前
|
存储 监控 安全
Python剪贴板监控实战:clipboard-monitor库的深度解析与扩展应用
本文介绍了基于Python的剪贴板监控技术,结合clipboard-monitor库实现高效、安全的数据追踪。内容涵盖技术选型、核心功能开发、性能优化及实战应用,适用于安全审计、自动化办公等场景,助力提升数据管理效率与安全性。
103 0
|
2月前
|
数据采集 索引 Python
Python Slice函数使用教程 - 详解与示例 | Python切片操作指南
Python中的`slice()`函数用于创建切片对象,以便对序列(如列表、字符串、元组)进行高效切片操作。它支持指定起始索引、结束索引和步长,提升代码可读性和灵活性。
|
12月前
|
数据可视化 IDE 开发工具
【Python篇】PyQt5 超详细教程——由入门到精通(中篇二)
【Python篇】PyQt5 超详细教程——由入门到精通(中篇二)
800 13

推荐镜像

更多