Python使用fnmatch模塊實(shí)現(xiàn)文件名匹配?針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
fnmatch 模塊主要用于文件名稱的匹配,其能力比簡單的字符串匹配更強(qiáng)大,但比使用正則表達(dá)式相比稍弱。。如果在數(shù)據(jù)處理操作中,只需要使用簡單的通配符就能完成文件名的匹配,則使用 fnmatch 模塊是不錯(cuò)的選擇。
fnmatch 模塊中,常用的函數(shù)及其功能如表 1 所示。
Python fnmatch模塊常用函數(shù)及功能
函數(shù)名 | 功能 |
fnmatch.filter(names, pattern) | 對 names 列表進(jìn)行過濾,返回 names 列表中匹配 pattern 的文件名組成的子集合。 |
fnmatch.fnmatch(filename, pattern) | 判斷 filename 文件名,是否和指定 pattern 字符串匹配 |
fnmatch.fnmatchcase(filename, pattern) | 和 fnmatch() 函數(shù)功能大致相同,只是該函數(shù)區(qū)分大小寫。 |
fnmatch.translate(pattern) | 將一個(gè) UNIX shell 風(fēng)格的 pattern 字符串,轉(zhuǎn)換為正則表達(dá)式 |
fnmatch 模塊匹配文件名的模式使用的就是 UNIX shell 風(fēng)格,其支持使用如下幾個(gè)通配符:
例如,下面程序演示表 1 中一些函數(shù)的用法及功能:
import fnmatch #filter() print(fnmatch.filter(['dlsf', 'ewro.txt', 'te.py', 'youe.py'], '*.txt')) #fnmatch() for file in ['word.doc','index.py','my_file.txt']: if fnmatch.fnmatch(file,'*.txt'): print(file) #fnmatchcase() print([addr for addr in ['word.doc','index.py','my_file.txt','a.TXT'] if fnmatch.fnmatchcase(addr, '*.txt')]) #translate() print(fnmatch.translate('a*b.txt'))
本文標(biāo)題:Python使用fnmatch模塊實(shí)現(xiàn)文件名匹配-創(chuàng)新互聯(lián)
文章起源:http://www.yijiale78.com/article34/ceespe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、網(wǎng)站設(shè)計(jì)公司、響應(yīng)式網(wǎng)站、Google、App開發(fā)、用戶體驗(yàn)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容