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/']
目录
相关文章
|
1月前
|
JSON 数据可视化 API
Python 中调用 DeepSeek-R1 API的方法介绍,图文教程
本教程详细介绍了如何使用 Python 调用 DeepSeek 的 R1 大模型 API,适合编程新手。首先登录 DeepSeek 控制台获取 API Key,安装 Python 和 requests 库后,编写基础调用代码并运行。文末包含常见问题解答和更简单的可视化调用方法,建议收藏备用。 原文链接:[如何使用 Python 调用 DeepSeek-R1 API?](https://apifox.com/apiskills/how-to-call-the-deepseek-r1-api-using-python/)
|
2月前
|
机器学习/深度学习 存储 数据挖掘
Python图像处理实用指南:PIL库的多样化应用
本文介绍Python中PIL库在图像处理中的多样化应用,涵盖裁剪、调整大小、旋转、模糊、锐化、亮度和对比度调整、翻转、压缩及添加滤镜等操作。通过具体代码示例,展示如何轻松实现这些功能,帮助读者掌握高效图像处理技术,适用于图片美化、数据分析及机器学习等领域。
90 20
|
5天前
|
SQL 关系型数据库 MySQL
milvus-use教程 python
本项目参考vanna项目,获取数据库元数据和问题SQL对,存入Milvus向量数据库,并进行相似性检索。采用m3e-large嵌入模型,通过DatabaseManager类实现数据库连接持久化,MilvusVectorStore类封装了Milvus操作方法,如创建集合、添加数据和查询。项目提供init_collections、delete_collections等文件用于初始化、删除和管理集合。所用Milvus版本较新,API与vanna项目不兼容。 [项目地址](https://gitee.com/alpbeta/milvus-use)
63 9
|
25天前
|
数据采集 JavaScript Android开发
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
54 7
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
2月前
|
测试技术 Python
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
150 31
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
|
10天前
|
人工智能 自然语言处理 Shell
[oeasy]python070_如何导入模块_导入模块的作用_hello_dunder_双下划线
本文介绍了如何在Python中导入模块及其作用,重点讲解了`__hello__`模块的导入与使用。通过`import`命令可以将外部模块引入当前环境,增强代码功能。例如,导入`__hello__`模块后可输出“Hello world!”。此外,还演示了如何使用`help()`和`dir()`函数查询模块信息,并展示了导入多个模块的方法。最后,通过一个实例,介绍了如何利用`jieba`、`WordCloud`和`matplotlib`模块生成词云图。总结来说,模块是封装好的功能部件,能够简化编程任务并提高效率。未来将探讨如何创建自定义模块。
30 8
|
7天前
|
缓存 Shell 开发工具
[oeasy]python071_我可以自己做一个模块吗_自定义模块_引入模块_import_diy
本文介绍了 Python 中模块的导入与自定义模块的创建。首先,我们回忆了模块的概念,即封装好功能的部件,并通过导入 `__hello__` 模块实现了输出 &quot;hello world!&quot; 的功能。接着,尝试创建并编辑自己的模块 `my_file.py`,引入 `time` 模块以获取当前时间,并在其中添加自定义输出。
20 4
|
11天前
|
大数据 开发者 C++
Python语法糖详解教程
《Python语法糖详解教程》介绍了编程语言中的“语法糖”,即通过特殊语法形式简化代码,使代码更简洁、易读和高效。文章详细解析了列表推导式、字典推导式、元组解包、条件表达式、with语句和装饰器等核心语法糖,并提供了具体示例和最佳实践指南。通过这些技巧,开发者可以在保持底层功能不变的前提下,显著提升开发效率和代码质量。
33 8
|
2月前
|
IDE 测试技术 项目管理
【新手必看】PyCharm2025 免费下载安装配置教程+Python环境搭建、图文并茂全副武装学起来才嗖嗖的快,绝对最详细!
PyCharm是由JetBrains开发的Python集成开发环境(IDE),专为Python开发者设计,支持Web开发、调试、语法高亮、项目管理、代码跳转、智能提示、自动完成、单元测试和版本控制等功能。它有专业版、教育版和社区版三个版本,其中社区版免费且适合个人和小型团队使用,包含基本的Python开发功能。安装PyCharm前需先安装Python解释器,并配置环境变量。通过简单的步骤即可在PyCharm中创建并运行Python项目,如输出“Hello World”。
368 13
【新手必看】PyCharm2025 免费下载安装配置教程+Python环境搭建、图文并茂全副武装学起来才嗖嗖的快,绝对最详细!
|
13天前
|
C语言 Python
Python学习:内建属性、内建函数的教程
本文介绍了Python中的内建属性和内建函数。内建属性包括`__init__`、`__new__`、`__class__`等,通过`dir()`函数可以查看类的所有内建属性。内建函数如`range`、`map`、`filter`、`reduce`和`sorted`等,分别用于生成序列、映射操作、过滤操作、累积计算和排序。其中,`reduce`在Python 3中需从`functools`模块导入。示例代码展示了这些特性和函数的具体用法及注意事项。

热门文章

最新文章

推荐镜像

更多