fnmatch提供了一种类似 Unix shell-style
风格的文件名匹配方式
匹配模式
* 匹配任何字符
? 匹配一个字符
[seq] 匹配在集合seq 中的任意字符
[!seq] 匹配不在集合seq 中的任意字符
代码示例
import fnmatch
filenames = [
"China.txt",
"Japan.txt",
"America.py",
"Korea.conf",
]
# fnmatch 和 fnmatchcase 匹配文件,区别不太明显
for filename in filenames:
if fnmatch.fnmatch(filename, '*.txt'):
print(filename)
"""
China.txt
Japan.txt
"""
for filename in filenames:
if fnmatch.fnmatchcase(filename, '*.txt'):
print(filename)
"""
China.txt
Japan.txt
"""
# filter 过滤符合的文件
filenames = fnmatch.filter(filenames, "*.txt")
# 类似:[n for n in names if fnmatch(n, pattern)]
print(filenames)
# ['China.txt', 'Japan.txt']
# translate 翻译成re 正则表达式
print(fnmatch.translate("*.txt"))
# (?s:.*\.conf)\Z