【转】Python模块学习 - fnmatch & glob

【转】Python模块学习 - fnmatch & glob

介绍

  fnmatch 和 glob 模块都是用来做字符串匹配文件名的标准库。

fnmatch模块

  大部分情况下使用字符串匹配查找特定的文件就能满足需求,如果需要更加灵活的字符串匹配,就没有办法了,这里介绍标准库fnmatch。这个库专门用来做文件名匹配

fnmatch支持的通配符

  fnmatch支持的通配如下:

通配符      含义     
* 匹配任何数量的字符
匹配单个字符
[seq] 匹配seq中的字符
[!seq] 匹配除seq以外的任何字符

fnmatch的基本使用

  fnmatch这个库相对比较简单,只有4个函数,分别是fnmatch、fnmatchcase、filter和translate,其中最常用的是fnmatch。主要功能如下:

    • fnmatch:判断文件名是否符合特定的模式。
    • fnmatchcase:判断文件名是否符合特定的模式,区分大小写。
    • filter:返回输入列表中,符合特定模式的文件名列表。
    • translate:将通配符模式转换成正则表达式。

例子

  fnmatch和fnmatchcase用法相同,判断名称是否符合表达式,返回True or False

>>> os.listdir(os.curdir)
['A1.jpg', 'a1.txt', 'a2.txt', 'aA.txt', 'b3.jpg', 'b2.jpg', 'b1.jpg']

>>> [ name for name in os.listdir(os.curdir) if fnmatch.fnmatch(name,'*.jpg') ]
['A1.jpg', 'b3.jpg', 'b2.jpg', 'b1.jpg']

>>> [ name for name in os.listdir(os.curdir) if fnmatch.fnmatch(name,"[ab]*") ]
['a1.txt', 'a2.txt', 'aA.txt', 'b3.jpg', 'b2.jpg', 'b1.jpg']

>>> [ name for name in os.listdir(os.curdir) if fnmatch.fnmatch(name,"[!a]*") ]
['A1.jpg', 'b3.jpg', 'b2.jpg', 'b1.jpg']

>>> [ name for name in os.listdir(os.curdir) if fnmatch.fnmatch(name,"b?.jpg") ]
['b3.jpg', 'b2.jpg', 'b1.jpg']

>>> [ name for name in os.listdir(os.curdir) if fnmatch.fnmatchcase(name,"A?.jpg") ]
['A1.jpg']

  filter和fnmatch类似,只不过filter接受的第一个参数是一个文件名列表,返回符合表达式的列表(即:筛选)

>>> name = os.listdir(os.curdir)
>>> name
['A1.jpg', 'a1.txt', 'a2.txt', 'aA.txt', 'b3.jpg', 'b2.jpg', 'b1.jpg']
>>> fnmatch.filter(name,'*.txt')
['a1.txt', 'a2.txt', 'aA.txt']
>>> 

glob模块

  我们前面的fnmatch模块,都是利用os.listdir获取文件列表,然后通过字符串fnmatch模块进行文件名匹配的,而在Python中还有更加简单的方式,即使用glob库。

  glob的作用就相当于os.listdir 加上 fnmatch。使用glob以后就不用使用os.listdir获取文件列表了。

  glob比fnmatch更简单,因为他只有 glob,iglob,escape三个函数。

glob基本使用

glob和iglob的区别在于glob返回的是一个列表,iglob返回的是一个生成器对象

>>> import glob
>>> glob.glob('*.txt')
['a1.txt', 'a2.txt', 'aA.txt']

>>> g = glob.iglob('*.txt')        # 使用iglob返回的是一个生成器
>>> g
<generator object _iglob at 0x1050bbba0>

>>> list(g)
['a1.txt', 'a2.txt', 'aA.txt']
>>> 

PS:glob同样支持通配符和fnmatch相同,这里不在列举,并且在通配符表达式中支持路径

>>> glob.glob('/Users/DahlHin/github/test/*.txt')
['/Users/DahlHin/github/test/a1.txt','/Users/DahlHin/github/test/a2.txt','/Users/DahlHin/github/test/aA.txt']
>>> 

猜你喜欢

转载自www.cnblogs.com/langqi250/p/10260426.html