淺析python標(biāo)準(zhǔn)庫(kù)中的glob
glob 文件名模式匹配,不用遍歷整個(gè)目錄判斷每個(gè)文件是不是符合。
1、通配符
星號(hào)(*)匹配零個(gè)或多個(gè)字符
import globfor name in glob.glob(’dir/*’): print (name)dir/file.txtdir/file1.txtdir/file2.txtdir/filea.txtdir/fileb.txtdir/subdir
列出子目錄中的文件,必須在模式中包括子目錄名:
import glob#用子目錄查詢(xún)文件print (’Named explicitly:’)for name in glob.glob(’dir/subdir/*’): print (’t’, name)#用通配符* 代替子目錄名print (’Named with wildcard:’)for name in glob.glob(’dir/*/*’): print (’t’, name)Named explicitly: dir/subdir/subfile.txtNamed with wildcard: dir/subdir/subfile.txt
2、單個(gè)字符通配符
用問(wèn)號(hào)(?)匹配任何單個(gè)的字符。
import globfor name in glob.glob(’dir/file?.txt’): print (name)dir/file1.txtdir/file2.txtdir/filea.txtdir/fileb.txt
3、字符范圍
當(dāng)需要匹配一個(gè)特定的字符,可以使用一個(gè)范圍
import globfor name in glob.glob(’dir/*[0-9].*’): print (name)dir/file1.txtdir/file2.txt
知識(shí)點(diǎn)補(bǔ)充:Python編程:glob模塊進(jìn)行文件名模式匹配
文件準(zhǔn)備
$ mkdir tmp$ cd tmp$ touch file1.txt$ touch file2.txt$ touch file3.log$ lsfile1.txt file2.txt file3.log
測(cè)試
import glob# 使用零個(gè)或多個(gè)字符通配符 * glob.glob('tmp/*.txt')Out[1]: [’file1.txt’, ’file2.txt’]# 使用單字符通配符 ?glob.glob('tmp/file?.txt')Out[2]: [’file1.txt’, ’file2.txt’]# 使用范圍匹配glob.glob('tmp/file[0-9].txt')Out[3]: [’file1.txt’, ’file2.txt’]
總結(jié)
到此這篇關(guān)于淺析python標(biāo)準(zhǔn)庫(kù)中的glob的文章就介紹到這了,更多相關(guān)python標(biāo)準(zhǔn)庫(kù) glob內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))2. .Net反向代理組件Yarp用法詳解3. 解決request.getParameter取值后的if判斷為NULL的問(wèn)題4. .NET Framework各版本(.NET2.0 3.0 3.5 4.0)區(qū)別5. 詳解JSP 內(nèi)置對(duì)象request常見(jiàn)用法6. JSP中param動(dòng)作的實(shí)例詳解7. ASP.NET MVC實(shí)現(xiàn)下拉框多選8. ASP.NET MVC增加一條記錄同時(shí)添加N條集合屬性所對(duì)應(yīng)的個(gè)體9. .NET中的MassTransit分布式應(yīng)用框架詳解10. ASP.NET MVC實(shí)現(xiàn)本地化和全球化
