Python 中的 fnmatch 模块

Vaibhav Vaibhav 2023年10月10日
Python 中的 fnmatch 模块

在处理文件和文件系统时,经常需要从一堆文件中找到几个文件。如果手动执行,从一堆文件中查找所需文件将花费很长时间。

因此,操作系统和编程语言提供了用于动态查找所需文件的实用程序。这些实用程序倾向于以文件名为目标,并尝试在模式匹配的帮助下找到必要的文件。

在诸如 macOS 和 Linux 等基于 UNIX 的操作系统中,可以借助 Python 编程语言中的 fnmatch 库来定位文件。

本文将学习如何使用 Python 的 fnmatch 库执行模式匹配。

Python 中的 fnmatch 模块

fnmatch 模块用于匹配 UNIX 操作系统 shell 样式的通配符。请注意,这些样式不是 regexregular 表达式。

以下是 UNIX shell-style wildcards 中使用的特殊字符:

模式 操作
* 匹配一切
? 匹配单个字符
[sequence] 匹配序列中的任何字符
[!sequence] 匹配任何字符,而不是按顺序

fnmatch 库有以下方法:

  • fnmatch.fnmatch(filename, pattern)fnmatch() 方法,将文件名与指定模式匹配。如果模式匹配,则返回 True;否则,。请注意,此方法不区分大小写,并且在 os.path.normcase() 方法的帮助下,两个参数都被标准化为小写。
  • fnmatch.fnmatchcase(filename, pattern) - 与 fnmatch() 方法非常相似,但它区分大小写并且不对参数应用 os.path.normcase() 方法。
  • fnmatch.filter(names, pattern) 创建与指定模式匹配的文件名列表。此方法类似于遍历所有文件名并执行 fnmatch() 方法,但实现效率更高。
  • fnmatch.translate(pattern)re.match() 方法的帮助下将 shell 样式模式转换为正则表达式或正则表达式。

现在我们已经了解了一些理论,让我们在相关示例的帮助下了解如何实际使用这个库。

该示例过滤所有以 .html 扩展名结尾的文件。

import os
import fnmatch

for file in os.listdir("."):
    if fnmatch.fnmatch(file, "*.html"):
        print(file)

输出:

<files with ".html" extension in the current working directory>

上面的 Python 代码首先在 os.listdir() 方法的帮助下读取当前工作目录中的所有文件。接下来,它遍历所有文件并使用 fnmatch() 方法检查它们是否是 HTML 文件。

这里,*.html 模式匹配所有以 .html 结尾的文件。这里,* 是指文件名中的任意数量的字符。

让我们看另一个过滤所有以 hello 开头并以 .js 结尾的文件的示例。请参阅以下 Python 代码。

import os
import fnmatch

for file in os.listdir("."):
    if fnmatch.fnmatch(file, "hello*.js"):
        print(file)

输出:

<files with filenames of type "hello*.js" in the current working directory>
作者: Vaibhav Vaibhav
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

相关文章 - Python Module