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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM