Doc: https://docs.python.org/2/library/fnmatch.html#module-fnmatch
fnmatch用来判断文件名模块是否匹配”Unix shell-style wildcards”, 可用通配符*?[seq][!seq]
实际所谓文件名,就是一个字符串, 这跟re模块的功能差不多,区别在于通配符表达式和正则表达式的不一样。
所以fnmatch模块有个translate()函数,就是把通配符表达式翻译成正则表大家式,比如*就变成.*
函数:
fnmatch.fnmatch(filename, pattern), 返回True/False
fnmatch.fnmatchcase(filename, pattern), 返回True/False, 针对windows这样的对文件名大小写不区分的系统,做强制大小写检查,比如fnmatch.fnmatchcase(‘abc.txt, ‘*.TXT’), 返回False。 在linux下与fnmatch.fnmatch()没有区别。
fnmatch.filter(filenames, pattern) , 返回一个list, 这个list是匹配pattern的filenames list 里的文件组成, 没有一个匹配就返回空list []
fnmatch.translate(pattern), 把Unix shell-style wildcards pattern 转成正则表达式
程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import fnmatch import os import re for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): print file print '-----------------------------' for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.Txt'): print file print '-----------------------------' for file in os.listdir('.'): if fnmatch.fnmatchcase(file, '*.txt'): print file print '-----------------------------' for file in os.listdir('.'): if fnmatch.fnmatch(file, '[!a]*.txt'): print file print '-----------------------------' filename = "abc123.txt" if fnmatch.fnmatch(filename, '[a-b]*.txt'): print filename, " match" print '-----------------------------' files = fnmatch.filter(os.listdir('.'), '*.txt') print files print '-----------------------------' regex = fnmatch.translate('*.txt') print regex reobj = re.compile(regex) reobj.match('abc123.txt') print reobj |
结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
args.txt temp.txt ----------------------------- ----------------------------- args.txt temp.txt ----------------------------- temp.txt ----------------------------- abc123.txt match ----------------------------- ['args.txt', 'temp.txt'] ----------------------------- .*\.txt\Z(?ms) <_sre.SRE_Pattern object at 0x76cf4d68> |