fnmatch 模块主要用于文件名称的匹配,其能力比简单的字符串匹配更强大,但比使用正则表达式相比稍弱。。如果在数据处理操作中,只需要使用简单的通配符就能完成文件名的匹配,则
          fnmatch 模块中,常用的函数及其功能如表 1 所示。
fnmatch 模块匹配文件名的模式使用的就是 UNIX shell 风格,其支持使用如下几个通配符:
- *:可匹配任意个任意字符。
 - ?:可匹配一个任意字符。
 - [字符序列]:可匹配中括号里字符序列中的任意字符。该字符序列也支持中画线表示法。比如 [a-c] 可代表 a、b 和 c 字符中任意一个。
 - [!字符序列]:可匹配不在中括号里字符序列中的任意字符。
 
例如,下面程序演示表 1 中一些函数的用法及功能:
import fnmatch
#filter()
print(fnmatch.filter(['dlsf', 'ewro.txt', 'te.py', 'youe.py'], '*.txt'))
#fnmatch()
for file in ['word.doc','index.py','my_file.txt']:
    if fnmatch.fnmatch(file,'*.txt'):
        print(file)
 
#fnmatchcase()
print([addr for addr in ['word.doc','index.py','my_file.txt','a.TXT'] if fnmatch.fnmatchcase(addr, '*.txt')])
#translate()
print(fnmatch.translate('a*b.txt'))
程序执行结果为:
['ewro.txt']
my_file.txt
['my_file.txt']
(?s:a.*b\.txt)\Z
