fnmatch --- Unix 文件�模�匹�¶

�代�: Lib/fnmatch.py


此模��供了 Unix shell 风格的通�符,它们 并� 等�于正则表达�(关于�者的文档�� re 模�)。 shell 风格通�符所使用的特殊字符如下:

模�

��

*

匹�所有

?

匹�任何�个字符

[seq]

匹� seq 中的任何字符

[!seq]

匹�任何�在 seq 中的字符

对于字�值匹�,请将原字符用方括�括起�。 例如,'[?]' 将匹�字符 '?'。

注�文件�分隔符 (Unix 上为 '/') �会 被此模�特别对待。 请�� glob 模�了解文件�扩展 (glob 使用 filter() �匹�文件�的�个部分)。 类似地,以一个�点打头的文件�也�会被此模�特别对待,�以通过 * 和 ? 模��匹�。

还�注�是使用将 maxsize 设为 32768 的 functools.lru_cache() �缓存下列函数中的已编译正则表达�: fnmatch(), fnmatchcase(), filter()。

fnmatch.fnmatch(name, pat)¶

检测文件�字符串 name 是�匹�模�字符串 pat,返回 True 或 False。 两个形�都会使用 os.path.normcase() 进行大�写正规化。 fnmatchcase() �被用于执行大�写�感的比较,无论这是�为所在�作系统的标准。can be used to perform a case-sensitive comparison, regardless of whether that's standard for the operating system.

这个例�将打�当�目录下带有扩展� .txt 的所有文件�:

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
fnmatch.fnmatchcase(name, pat)¶

检测文件�字符串 name 是�匹�模�字符串 pat,返回 True 或 False;此比较是大�写�感的并且�会应用 os.path.normcase()。

fnmatch.filter(names, pat)¶

基于 iterable names 中匹�模� pat 的元素构造一个列表。 它等价于 [n for n in names if fnmatch(n, pat)],但实现得更为高效。

fnmatch.translate(pat)¶

返回由 shell 风格的模� pat 转��的正则表达�以便用于 re.match()。

示例:

>>> import fnmatch, re
>>>
>>> regex = fnmatch.translate('*.txt')
>>> regex
'(?s:.*\\.txt)\\Z'
>>> reobj = re.compile(regex)
>>> reobj.match('foobar.txt')
<re.Match object; span=(0, 10), match='foobar.txt'>

��

模� glob

Unix shell 风格路径扩展。