周末研究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()函数以外,还有以下几个常用的函数:
Test whether filename matches pattern, returning True or False; the comparison is case-sensitive.
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.
Return the shell-style pattern converted to a regular expression.Be aware there is no way to quote meta-characters.
>>> import fnmatch, re
>>>
>>> regex = fnmatch.translate('*.txt')
>>> regex
'.*\\.txt$'
>>> reobj = re.compile(regex)
>>> reobj.match('foobar.txt')
<_sre.SRE_Match object at 0x...>