Python: glob匹配文件的操作
glob模塊實(shí)例詳解
glob的應(yīng)用場(chǎng)景是要尋找一系列(符合特定規(guī)則)文件名。
glob模塊是最簡(jiǎn)單的模塊之一,內(nèi)容非常少。用它可以查找符合特定規(guī)則的文件路徑名。查找文件只用到三個(gè)匹配符:”*”, “?”, “[]”。
”*”匹配0個(gè)或多個(gè)字符;
”?”匹配單個(gè)字符;
”[ ]”匹配指定范圍內(nèi)的字符,如:[0-9]匹配數(shù)字。
假設(shè)以下例子目錄是這樣的。
dirdir/file.txtdir/file1.txtdir/file2.txtdir/filea.txtdir/fileb.txtdir/subdirdir/subdir/subfile.txt
匹配所有文件
可以用*匹配任意長(zhǎng)度字節(jié)。glob.glob比較常用,返回一個(gè)list,也可用glob.iglob返回生成器。
import globfor name in glob.glob(’dir/*’): print name
dir/file.txtdir/file1.txtdir/file2.txtdir/filea.txtdir/fileb.txtdir/subdir
匹配子目錄文件
可以指定子目錄名稱(chēng),也可以用通配符代替,不顯示指定。
print ’Named explicitly:’for name in glob.glob(’dir/subdir/*’): print ’t’, nameprint ’Named with wildcard:’for name in glob.glob(’dir/*/*’): print ’t’, name
Named explicitly: dir/subdir/subfile.txtNamed with wildcard: dir/subdir/subfile.txt
單字節(jié)通配符匹配
除了*以外,還有?匹配單個(gè)字符。比如下面這個(gè)例子,匹配以file開(kāi)頭,以.txt結(jié)尾,中間是任一字符的文件。
for name in glob.glob(’dir/file?.txt’):
print name
dir/file1.txtdir/file2.txtdir/filea.txtdir/fileb.txt
字符區(qū)間匹配[0-9]
比如匹配后綴前是數(shù)字的文件。
for name in glob.glob(’dir/*[0-9].*’):
print name
dir/file1.txt
dir/file2.txt
Ref:
官方文檔
Python Module of the Week
補(bǔ)充知識(shí):Python glob 遞歸遍歷匹配文件;os.makedirs()遞歸創(chuàng)建目錄
Glob遞歸遍歷匹配文件
簡(jiǎn)約版
在python中,glob模塊用來(lái)查找匹配文件
常用的匹配規(guī)則:
: 匹配所所有
? : 匹配一個(gè)字符
如果沒(méi)有匹配的,glob.glob(path)將返回一個(gè)空的list:[]
from glob import globfile_path = '/home/lihuiyu/Code/results_S2_W20040/*/*.pth'print(glob(file_path))
排序版
我喜歡偷懶,所以,Coding能解決的問(wèn)題一般不會(huì)人工解決;
我喜歡整潔,所以,Coding苛求完美,結(jié)果奢求整齊劃一。
import refrom glob import globdef atoi(s): return int(s) if s.isdigit() else sdef natural_keys(text): return [atoi(c) for c in re.split(’(d+)’, text)] file_path = '/home/lihuiyu/Code/results_S2_W20040/*/*.pth'file_list = glob(file_path)file_list.sort(key=natural_keys)for name in file_list: print(name)
os.makedirs()遞歸創(chuàng)建目錄
os.mkdir()創(chuàng)建指定的目錄,但如果其上一級(jí)目錄不存在,則無(wú)法創(chuàng)建成功。
os.makedirs()實(shí)現(xiàn)遞歸創(chuàng)建目錄的功能。
以上這篇Python: glob匹配文件的操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單2. Xml簡(jiǎn)介_(kāi)動(dòng)力節(jié)點(diǎn)Java學(xué)院整理3. Vue+elementUI下拉框自定義顏色選擇器方式4. 使用css實(shí)現(xiàn)全兼容tooltip提示框5. css進(jìn)階學(xué)習(xí) 選擇符6. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案7. CSS hack用法案例詳解8. 詳解盒子端CSS動(dòng)畫(huà)性能提升9. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)10. 小技巧處理div內(nèi)容溢出
