Python: fnmatch模块 (Unix B-Shell通配符的文件名匹配)

周末研究Robot Framework的源码来提高和保持python的编码能力。
在分析源码文件 pythonpathsetter.py的时候遇到了fnmatch模块,由于之前一般都是采用re模块来进行模式匹配,查了一下Python manual还是收获了欣喜,原来在某些场景下使用re不一定是最好的选择。

从名字来看,不难猜出其用途:File Name Match。


这个模块用于支持Unix B-Shell风格的通配符,再具体点想想make支持三各通配符:“*”,“?”和“[...]”,具体的含义如下:

Pattern

Meaning

*

matches everything

?

matches any single character

[seq]

matches any character in seq

[!seq]

matches any character not in seq


下面言归正传:

import fnmatch

fnmatch.fnmatch(filename, pattern)

Test whether the filename string matches the pattern string, returning True or False. If the operating system is case-insensitive, then both parameters will be normalized to all lower- or upper-case before the comparison is performed.


这个函数的作用是测试filename是否符合pattern。函数的返回值是True或者False。有些操作系统的文件名是大小敏感的,有些则不然,因此这个函数对传入的两个参数都会被统一化处理。
常用的场景如下:
import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file

除了最常用的fnmatch.fnmatch()函数以外,还有以下几个常用的函数:
   
   
fnmatch.fnmatchcase(filename, pattern)
Test whether filename matches pattern, returning True or False; the comparison is case-sensitive.

fnmatch.filter(names, pattern)
Return the subset of the list of names that match pattern. It is the same as [n for n in names if fnmatch(n, pattern)], but implemented more efficiently. New in version 2.2.

fnmatch.translate(pattern)
Return the shell-style pattern converted to a regular expression.Be aware there is no way to quote meta-characters.

Example:
>>> import fnmatch, re
>>>
>>> regex = fnmatch.translate('*.txt')
>>> regex
'.*\\.txt$'
>>> reobj = re.compile(regex)
>>> reobj.match('foobar.txt')
<_sre.SRE_Match object at 0x...>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值