fnmatch模块的使用

640?wx_fmt=gif

点击上方蓝字关注

fnmatch模块的使用

此模块的主要作用是文件名称的匹配,并且匹配的模式使用的unix shell风格。

640?wx_fmt=jpeg

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'>

640?wx_fmt=gif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值