此模块的主要作用是文件名称的匹配,并且匹配的模式使用的unix shell风格。fnmatch比较简单就4个方法分别是:fnmatch,fnmatchcase,filter,translate
fnmatch.fnmatch(filename, pattern)测试filename,是否符合pattern。
import fnmatchimport osdef run(): for file in os.listdir('.'): #os.listdir返回指定的文件夹包含的文件或文件夹的名字的列表 if fnmatch.fnmatch(file, '*.py'): #判断是否有后缀为.py的文件,*代表文件名长度格式不限制。 print(file)if __name__ == '__main__': run()fnmatch.fnmatchcase(filename, pattern)和fnmatch()类似,只是fnmatchcase 强制区分大小写匹配,不管文件系统是否区分。
print(fnmatch.fnmatchcase("text.py","text.*")) #True print(fnmatch.fnmatchcase("Text.py", "text.*")) # False print(fnmatch.fnmatchcase("Text.Py", "*.py")) # False print(fnmatch.fnmatchcase("Text.Py", "*.Py")) # Truefnmatch.filter(names, pattern)实现列表特殊字符的过滤或筛选,返回符合匹配模式的字符列表,它的作用类似 [n for n in names if fnmatch(n, pattern)]
filelist=["a.text","b.jpg","c.png","d.py",'e.text',"sss.py"] print(fnmatch.filter(filelist,"?.py")) #匹配前面是一个字符的.py文件 输出:d.pyfnmatch.translate(pattern):翻译模式, fnmatch将这种全局模式转换成一个正则式, 然后使用re模块来比较名字和模式。 translate() 函数是一个公共API用于将全局模式转换成正则式
regex = fnmatch.translate('[f,d,d,d,g,h].txt')#将[f,d,d,d,g,h].txt转为正则匹配的模式print("regex",regex)#(?s:[f,d,d,d,g,h]\.txt)\Z#\Z:匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串。reobj = re.compile(regex)#生成re匹配模块print(reobj.match ('f.txt'))#返回一个匹配对象#<_sre.SRE_Match object; span=(0, 5), match='f.txt'>转载于:https://www.cnblogs.com/c-x-a/p/9261621.html
相关资源:JAVA上百实例源码以及开源项目