1.fnmatch():判断是否与指定的字符串匹配,格式:
fnmatch.fnmatch(file, '*.py'),file为字符串类型,其中*.py,可以简单的用类似正则来表示:
def run():
for file in os.listdir('.'): #os.listdir返回指定的文件夹包含的文件或文件夹的名字的列表
if fnmatch.fnmatch(file, '*.py'): #判断是否有后缀为.py的文件,*代表文件名长度格式不限制。
print(file)
2.fnmatchcase():区分大小写来进行匹配,格式:
fnmatch.fnmatchcase(“Text.Py”, '*.py")
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会去遍历列表中的每一个元素,格式:
fnmatch.filter(filelist,"?.py"),其中filelist是一个列表,遍历列表中的元素值来与?.py进行字符串的匹配。
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('[f,d,d,d,g,h].txt'),将要匹配的字符串转换成正则模式
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'))#返回一个匹配对象