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']
>>>
AI 代码解读

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
AI 代码解读

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
AI 代码解读

1、返回目录的路径列表

>>> path_list1 = glob.glob('./test_dir/')
>>> path_list
['./test_dir/']
AI 代码解读

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']
AI 代码解读

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

>>> path_list3 = glob.glob('./test_dir/*.py')
>>> path_list3
['./test_dir/a3.py']
AI 代码解读
>>> 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']
AI 代码解读

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']
AI 代码解读
>>> 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']
AI 代码解读

注意:

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

>>> path_list = glob.glob('./test_dir/', recursive=True)
>>> path_list
['./test_dir/']
AI 代码解读

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
AI 代码解读

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
AI 代码解读

正常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']
AI 代码解读

现在,使用: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
>>>
AI 代码解读

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/']
AI 代码解读
目录
打赏
0
0
0
0
12
分享
相关文章
通义灵码 Rules 库合集来了,覆盖Java、TypeScript、Python、Go、JavaScript 等
通义灵码新上的外挂 Project Rules 获得了开发者的一致好评:最小成本适配我的开发风格、相当把团队经验沉淀下来,是个很好功能……
929 103
Python网络请求库requests使用详述
总结来说,`requests`库非常适用于需要快速、简易、可靠进行HTTP请求的应用场景,它的简洁性让开发者避免繁琐的网络代码而专注于交互逻辑本身。通过上述方式,你可以利用 `requests`处理大部分常见的HTTP请求需求。
141 51
过三色刷脸技术,过三色刷脸技术教程,插件过人脸python分享学习
三色刷脸技术是基于RGB三通道分离的人脸特征提取方法,通过分析人脸在不同颜色通道的特征差异
用 Python 制作简单小游戏教程:手把手教你开发猜数字游戏
本教程详细讲解了用Python实现经典猜数字游戏的完整流程,涵盖从基础规则到高级功能的全方位开发。内容包括游戏逻辑设计、输入验证与错误处理、猜测次数统计、难度选择、彩色输出等核心功能,并提供完整代码示例。同时,介绍了开发环境搭建及调试方法,帮助初学者快速上手。最后还提出了图形界面、网络对战、成就系统等扩展方向,鼓励读者自主创新,打造个性化游戏版本。适合Python入门者实践与进阶学习。
116 1
Jupyter MCP服务器部署实战:AI模型与Python环境无缝集成教程
Jupyter MCP服务器基于模型上下文协议(MCP),实现大型语言模型与Jupyter环境的无缝集成。它通过标准化接口,让AI模型安全访问和操作Jupyter核心组件,如内核、文件系统和终端。本文深入解析其技术架构、功能特性及部署方法。MCP服务器解决了传统AI模型缺乏实时上下文感知的问题,支持代码执行、变量状态获取、文件管理等功能,提升编程效率。同时,严格的权限控制确保了安全性。作为智能化交互工具,Jupyter MCP为动态计算环境与AI模型之间搭建了高效桥梁。
210 2
Jupyter MCP服务器部署实战:AI模型与Python环境无缝集成教程
解决Python requests库POST请求参数顺序问题的方法。
总之,想要在Python的requests库里保持POST参数顺序,你要像捋顺头发一样捋顺它们,在向服务器炫耀你那有条不紊的数据前。抓紧手中的 `OrderedDict`与 `json`这两把钥匙,就能向服务端展示你的请求参数就像经过高端配置的快递包裹,里面的商品摆放井井有条,任何时候开箱都是一种享受。
60 10
|
1月前
|
分析参数顺序对Python requests库进行POST请求的影响。
最后,尽管理论上参数顺序对POST请求没影响,但编写代码时仍然建议遵循一定的顺序和规范,比如URL总是放在第一位,随后是data或json,最后是headers,这样可以提高代码的可读性和维护性。在处理复杂的请求时,一致的参数顺序有助于调试和团队协作。
98 9
|
3月前
|
Python教程:os 与 sys 模块详细用法
os 模块用于与操作系统交互,主要涉及夹操作、路径操作和其他操作。例如,`os.rename()` 重命名文件,`os.mkdir()` 创建文件夹,`os.path.abspath()` 获取文件绝对路径等。sys 模块则用于与 Python 解释器交互,常用功能如 `sys.path` 查看模块搜索路径,`sys.platform` 检测操作系统等。这些模块提供了丰富的工具,便于开发中处理系统和文件相关任务。
124 14

热门文章

最新文章

推荐镜像

更多
AI助理
登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问

你好,我是AI助理

可以解答问题、推荐解决方案等