python fnmatch模块学习

fnmatch 模块使用模式来匹配文件名。

模式语法和 Unix shell 中所使用的相同. 星号(*) 匹配零个或更多个字符,问号(?) 匹配单个字符. 你也可以使用方括号来指定字符范围, 例如 [0-9]代表一个数字. 其他所有字符都匹配它们本身。

fnmatch方法:

glob 事实上使用了 fnmatch 模块来完成模式匹配.

example:

#!/usr/bin/env python
import fnmatch
import os

for file in os.listdir(‘.’):
if fnmatch.fnmatch(file,’*.py’):
print file
 

运行结果:

netcat@netcat:~$ python a.py
a.py

translate 方法:

可以将一个文件匹配模式转换为正则表达式。

example:

#!/usr/bin/env python
import fnmatch
import os
import re

pattern=fnmatch.translate(‘*.py’)
print pattern
for file in os.listdir(‘.’):
if re.match(pattern,file):
print file
运行结果:

netcat@netcat:~$ python b.py
.*.py\Z(?ms)
a.py
b.py

 

re方法:

用法基本与re模块类似,所以不做介绍。

 

filter方法:

匹配符合的内容。

example:

#!/usr/bin/env python
import fnmatch
import os

for file in fnmatch.filter(os.listdir(‘.’),’*.py’):
print file
运行结果:

netcat@netcat:~$ python c.py
a.py
b.py
c.py