新聞中心
fnmatch —- Unix 文件名模式匹配
源代碼: Lib/fnmatch.py

成都創(chuàng)新互聯(lián)公司總部坐落于成都市區(qū),致力網(wǎng)站建設(shè)服務有網(wǎng)站設(shè)計、成都網(wǎng)站設(shè)計、網(wǎng)絡(luò)營銷策劃、網(wǎng)頁設(shè)計、網(wǎng)站維護、公眾號搭建、成都小程序開發(fā)、軟件開發(fā)等為企業(yè)提供一整套的信息化建設(shè)解決方案。創(chuàng)造真正意義上的網(wǎng)站建設(shè),為互聯(lián)網(wǎng)品牌在互動行銷領(lǐng)域創(chuàng)造價值而不懈努力!
此模塊提供了 Unix shell 風格的通配符,它們 并不 等同于正則表達式(關(guān)于后者的文檔參見 re 模塊)。 shell 風格通配符所使用的特殊字符如下:
|
模式 |
含意 |
|---|---|
|
|
匹配所有 |
|
|
匹配任何單個字符 |
|
|
匹配 seq 中的任何字符 |
|
|
匹配任何不在 seq 中的字符 |
對于字面值匹配,請將原字符用方括號括起來。 例如,'[?]' 將匹配字符 '?'。
注意文件名分隔符 (Unix 上為 '/') 不會 被此模塊特別對待。 請參見 glob 模塊了解文件名擴展 (glob 使用 filter() 來匹配文件名的各個部分)。 類似地,以一個句點打頭的文件名也不會被此模塊特別對待,可以通過 * 和 ? 模式來匹配。
Also note that functools.lru_cache() with the maxsize of 32768 is used to cache the compiled regex patterns in the following functions: fnmatch(), fnmatchcase(), filter().
fnmatch.fnmatch(filename, pattern)
檢測 filename 字符串是否匹配 pattern 字符串,返回 True 或 False。 兩個形參都會使用 os.path.normcase() 進行大小寫正規(guī)化。 fnmatchcase() 可被用于執(zhí)行大小寫敏感的比較,無論這是否為所在操作系統(tǒng)的標準。
這個例子將打印當前目錄下帶有擴展名 .txt 的所有文件名:
import fnmatchimport osfor file in os.listdir('.'):if fnmatch.fnmatch(file, '*.txt'):print(file)
fnmatch.fnmatchcase(filename, pattern)
檢測 filename 是否匹配 pattern,返回 True 或 False;此比較是大小寫敏感的,并且不會應用 os.path.normcase()。
fnmatch.filter(names, pattern)
基于可迭代對象 names 中匹配 pattern 的元素構(gòu)造一個列表。 它等價于 [n for n in names if fnmatch(n, pattern)],但實現(xiàn)得更有效率。
fnmatch.translate(pattern)
返回 shell 風格 pattern 轉(zhuǎn)換成的正則表達式以便用于 re.match()。
示例:
>>> import fnmatch, re>>>>>> regex = fnmatch.translate('*.txt')>>> regex'(?s:.*\\.txt)\\Z'>>> reobj = re.compile(regex)>>> reobj.match('foobar.txt')
參見
模塊 glob
Unix shell 風格路徑擴展。
本文名稱:創(chuàng)新互聯(lián)Python教程:fnmatch—-Unix文件名模式匹配
當前地址:http://fisionsoft.com.cn/article/dpecidg.html


咨詢
建站咨詢
