点击上方蓝字关注
fnmatch模块的使用
此模块的主要作用是文件名称的匹配,并且匹配的模式使用的unix shell风格。
1.fnmatch
fnmatch.fnmatch(filename, pattern)
import fnmatch
import os
def run():
for file in os.listdir('.'): #os.listdir返回指定的文件夹包含的文件或文件夹的名字的列表
if fnmatch.fnmatch(file, '*.py'): #判断是否有后缀为.py的文件,*代表文件名长度格式不限制。
print(file)
if __name__ == '__main__':
run()
2.fnmatchcase
fnmatch.fnmatchcase(filename, pattern)
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")) # True
3.filter
fnmatch.filter(names, pattern)
filelist=["a.text","b.jpg","c.png","d.py",'e.text',"sss.py"]
print(fnmatch.filter(filelist,"?.py")) #匹配前面是一个字符的.py文件
输出:d.py
4.translate
fnmatch.translate(pattern):
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'>