99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀開眼界!Python遍歷文件可以這樣做
開眼界!Python遍歷文件可以這樣做
2021-03-23
收藏

來源:【公眾號(hào)】

Python技術(shù)

開眼界!Python遍歷文件可以這樣做

Python 對(duì)于文件夾或者文件的遍歷一般有兩種操作方法,一種是至二級(jí)利用其封裝好的 walk 方法操作:

import os for root,dirs,files in os.walk("/Users/cxhuan/Downloads/globtest/hello"):
    for dir in dirs:
        print(os.path.join(root, dir))
    for file in files:
        print(os.path.join(root, file))

上面代碼運(yùn)行結(jié)果如下:

/Users/cxhuan/Downloads/globtest/hello/world /Users/cxhuan/Downloads/globtest/hello/.DS_Store
/Users/cxhuan/Downloads/globtest/hello/hello3.txt
/Users/cxhuan/Downloads/globtest/hello/hello2.txt
/Users/cxhuan/Downloads/globtest/hello/hello1.txt
/Users/cxhuan/Downloads/globtest/hello/world/world1.txt
/Users/cxhuan/Downloads/globtest/hello/world/world3.txt
/Users/cxhuan/Downloads/globtest/hello/world/world2.txt

上述程序,將 os.walk 讀取到的所有路徑 root 、目錄名 dirs 與文件名 files ,也就是三個(gè)文件數(shù)組利用 foreach 循環(huán)輸出。join方法就是將其路徑與目錄名或者文件名連接起來,組成一個(gè)完整的目錄。

另一種是用遞歸的思路,寫成下面的形式:

import os files = list()
def dirAll(pathname):
    if os.path.exists(pathname):
        filelist = os.listdir(pathname)
        for f in filelist:
            f = os.path.join(pathname, f)
            if os.path.isdir(f):
                dirAll(f)
            else:
                dirname = os.path.dirname(f)
                baseName = os.path.basename(f)
                if dirname.endswith(os.sep):
                    files.append(dirname+baseName)
                else:
                    files.append(dirname+os.sep+baseName)


dirAll("/Users/cxhuan/Downloads/globtest/hello") for f in files:
    print(f)

運(yùn)行上面代碼,得到的結(jié)果和上面一樣。

這兩種方法都沒問題,就是寫起來比較麻煩,特別是第二種,一不小心還有可能寫出 bug 。

今天我們來介紹第三種方法——利用 glob 模塊來遍歷文件。

簡(jiǎn)介

glob 是 python 自帶的一個(gè)操作文件的模塊,以簡(jiǎn)潔實(shí)用著稱。由于這個(gè)模塊的功能比較簡(jiǎn)單,所以也很容易上手和使用。它主要用來查找符合特定規(guī)則的文件路徑。使用這個(gè)模塊來查找文件,只需要用到*、? 和 [] 這三個(gè)匹配符:

 * : 匹配0個(gè)或多個(gè)字符;
 ? : 匹配單個(gè)字符;
 [] :匹配指定范圍內(nèi)的字符,如:[0-9]匹配數(shù)字。

glob.glob 方法

glob.glob 方法主要返回所有匹配的文件路徑列表。它只有一個(gè)參數(shù) pathname ,定義了文件路徑匹配規(guī)則,這里可以是絕對(duì)路徑,也可以是相對(duì)路徑。

使用 * 匹配

我們可以用 * 匹配零個(gè)或者多個(gè)字符。

輸出目錄下的子目錄或者文件:

for p1 in glob.glob('/Users/cxhuan/Downloads/globtest/*'):
    print(p1)

運(yùn)行上面代碼,會(huì)將 globtest 文件夾下僅有的目錄輸出出來,輸出內(nèi)容如下:

/Users/cxhuan/Downloads/globtest/hello

我們也可以通過制定層級(jí)來遍歷文件或者文件夾:

for p in glob.glob('/Users/cxhuan/Downloads/globtest/*/*'):
    print(p)

上面的代碼會(huì)遍歷 globtest 文件夾以及子文件夾,將所有的文件或文件夾路徑打印出來:

/Users/cxhuan/Downloads/globtest/hello/world
/Users/cxhuan/Downloads/globtest/hello/hello3.txt
/Users/cxhuan/Downloads/globtest/hello/hello2.txt
/Users/cxhuan/Downloads/globtest/hello/hello1.txt

我們也可以對(duì)文件或者文件夾進(jìn)行過濾:

for p in glob.glob('/Users/cxhuan/Downloads/globtest/hello/*3.txt'):
    print(p)

上面代碼值匹配 hello 目錄下的文件名末尾為 ‘3’ 的 txt 文件,運(yùn)行結(jié)果如下:

/Users/cxhuan/Downloads/globtest/hello/hello3.txt

使用 ? 匹配

我們可以用問號(hào)(?)匹配任何單個(gè)的字符。

for p in glob.glob('/Users/cxhuan/Downloads/globtest/hello/hello?.txt'):
    print(p)

上面的代碼輸出 hello 目錄下的以 ‘hello’ 開頭的 txt 文件,輸出結(jié)果如下:

/Users/cxhuan/Downloads/globtest/hello/hello3.txt
/Users/cxhuan/Downloads/globtest/hello/hello2.txt
/Users/cxhuan/Downloads/globtest/hello/hello1.txt

使用 [] 匹配

我們可以使用 [] 來匹配一個(gè)范圍:

for p in glob.glob('/Users/cxhuan/Downloads/globtest/hello/*[0-2].*'):
    print(p)

我們想要得到 hello 目錄下的文件名結(jié)尾數(shù)字的范圍為 0到2的文件,運(yùn)行上面代碼,獲得的輸出為:

/Users/cxhuan/Downloads/globtest/hello/hello2.txt
/Users/cxhuan/Downloads/globtest/hello/hello1.txt

glob.iglob 方法

python 的 glob 方法可以對(duì)文件夾下所有文件進(jìn)行遍歷,并返回一個(gè) list 列表。而 iglob 方法一次只獲取一個(gè)匹配路徑。下面是一個(gè)簡(jiǎn)單的例子來說明二者的區(qū)別:

p = glob.glob('/Users/cxhuan/Downloads/globtest/hello/hello?.*') print(p) print('----------------------')

p = glob.iglob('/Users/cxhuan/Downloads/globtest/hello/hello?.*') print(p)

運(yùn)行上面代碼,結(jié)果返回是:

['/Users/cxhuan/Downloads/globtest/hello/hello3.txt''/Users/cxhuan/Downloads/globtest/hello/hello2.txt',
 '/Users/cxhuan/Downloads/globtest/hello/hello1.txt'] ---------------------- <generator
 object _iglob at 0x1040d8ac0>

從上面的結(jié)果我們可以很容易看到二者的區(qū)別,前者返回的是一個(gè)列表,后者返回的是一個(gè)可迭代對(duì)象。

我們針對(duì)這個(gè)可迭代對(duì)象做一下操作看看:

p = glob.iglob('/Users/cxhuan/Downloads/globtest/hello/hello?.*') print(p.__next__()) print(p.__next__())

運(yùn)行結(jié)果如下:

/Users/cxhuan/Downloads/globtest/hello/hello3.txt
/Users/cxhuan/Downloads/globtest/hello/hello2.txt

我們可以看到,針對(duì)這個(gè)可迭代對(duì)象,我們一次可以獲取到一個(gè)元素。這樣做的好處是節(jié)省內(nèi)存,試想如果一個(gè)路徑下有大量的文件夾或者文件,我們使用這個(gè)迭代對(duì)象不用一次性全部獲取到內(nèi)存,而是可以慢慢獲取。

數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }