新聞中心
Python中的fnmatch模塊提供了用于文件名模式匹配的功能,fnmatch函數(shù)是該模塊中的核心函數(shù),用于檢查文件名是否與指定的模式匹配。

網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序設(shè)計(jì)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了永清免費(fèi)建站歡迎大家使用!
1、fnmatch函數(shù)的語法:
fnmatch.fnmatch(filename, pattern)
參數(shù)說明:
filename:要進(jìn)行匹配的文件名。
pattern:用于匹配的模式。
2、模式匹配規(guī)則:
‘*’:匹配任意長度的字符(包括0個(gè)字符)。
‘?’:匹配任意單個(gè)字符。
‘[seq]’:匹配seq中的任意一個(gè)字符。
‘[!seq]’:匹配不在seq中的任意一個(gè)字符。
3、示例:
import fnmatch
import os
獲取當(dāng)前目錄下的所有文件
files = os.listdir('.')
遍歷文件列表,使用fnmatch函數(shù)進(jìn)行模式匹配
for file in files:
if fnmatch.fnmatch(file, '*.txt'):
print(f'{file} 是一個(gè)文本文件')
elif fnmatch.fnmatch(file, '*.py'):
print(f'{file} 是一個(gè)Python文件')
else:
print(f'{file} 不是文本或Python文件')
4、使用通配符進(jìn)行模式匹配:
import fnmatch
import os
獲取當(dāng)前目錄下的所有文件
files = os.listdir('.')
使用通配符進(jìn)行模式匹配
patterns = ['*.txt', '*.py']
for pattern in patterns:
for file in files:
if fnmatch.fnmatch(file, pattern):
print(f'{file} 匹配模式 {pattern}')
5、使用正則表達(dá)式進(jìn)行模式匹配:
雖然fnmatch函數(shù)主要用于簡(jiǎn)單的文件名模式匹配,但也可以通過將正則表達(dá)式轉(zhuǎn)換為fnmatch模式來實(shí)現(xiàn)更復(fù)雜的匹配,可以使用re模塊的escape函數(shù)將正則表達(dá)式中的特殊字符轉(zhuǎn)義,然后將其插入到fnmatch模式中。
import fnmatch
import re
def regex_to_fnmatch(pattern):
return '*' + re.escape(pattern).replace('\*', '.*').replace('\?', '.') + '*'
將正則表達(dá)式轉(zhuǎn)換為fnmatch模式
regex_pattern = r'd+'
fnmatch_pattern = regex_to_fnmatch(regex_pattern)
使用轉(zhuǎn)換后的fnmatch模式進(jìn)行匹配
for file in os.listdir('.'):
if fnmatch.fnmatch(file, fnmatch_pattern):
print(f'{file} 匹配正則表達(dá)式 {regex_pattern}')
6、注意事項(xiàng):
fnmatch函數(shù)在匹配時(shí)不區(qū)分大小寫,如果需要區(qū)分大小寫,可以使用fnmatch.fnmatchcase函數(shù)。
fnmatch函數(shù)僅支持基本的文件名模式匹配,不支持正則表達(dá)式的全部功能,如果需要進(jìn)行更復(fù)雜的匹配,可以使用re模塊的正則表達(dá)式功能。
分享標(biāo)題:pythonfnmatch模塊
URL分享:http://www.fisionsoft.com.cn/article/cohoepi.html


咨詢
建站咨詢
