作用:
主要作用是文件名稱的匹配
字符 含義
* 匹配多個字符
? 匹配單個字符
[seq] 匹配指定范圍內(nèi)字符
[!seq] 匹配不在指定范圍內(nèi)的字符
匹配結(jié)果為布爾型數(shù)據(jù),True or False
eg:
1.fnmatch
查找本目錄下所有py文件:
import fnmatch,os
for filename in os.listdir(os.curdir):
if fnmatch.fnmatch(filename,"*.py"):
print(filename)
if fnmatch.fnmatch('hello', '?ello'): # 匹配模式為問號,及匹配一個任意字符
print("hello")
if fnmatch.fnmatch('hello', 'h[a-z]llo'): # 匹配模式為單個字符,在a-z之間
print("hello")
if fnmatch.fnmatch('1hello', '[!a-z]hello'): # 匹配模式為不能是a-z之間的字符
print("hello")
2.fnmatchcase
fnmatch.fnmatchcase(filename, pattern)
和fnmatch()類似,只是fnmatchcase 強(qiáng)制區(qū)分大小寫匹配,不管文件系統(tǒng)是否區(qū)分。
3.filter
fnmatch.filter(names, pattern)
實(shí)現(xiàn)列表特殊字符的過濾或篩選,返回符合匹配模式的字符列表,它的作用類似
[n for n in names if fnmatch(n, pattern)]
4.translate
fnmatch.translate(pattern):
翻譯模式, fnmatch將這種全局模式轉(zhuǎn)換成一個正則式, 然后使用re模塊來比較名字和模式。 translate() 函數(shù)是一個公共API用于將全局模式轉(zhuǎn)換成正則式