python讀取多層嵌套文件夾中的文件實(shí)例
由于工作安排,需要讀取多層文件夾下嵌套的文件,文件夾的結(jié)構(gòu)如下圖所示:
想到了遞歸函數(shù),使用python的os.path.isfile方法判斷當(dāng)前是不是可執(zhí)行文件,如果不是再用os.listdir方法將子目錄循環(huán)判斷。
代碼如下
import ospath = ’abc’path_read = [] #path_read saves all executable filesdef check_if_dir(file_path): temp_list = os.listdir(file_path) #put file name from file_path in temp_list for temp_list_each in temp_list: if os.path.isfile(file_path + ’/’ + temp_list_each): temp_path = file_path + ’/’ + temp_list_each if os.path.splitext(temp_path)[-1] == ’.log’: #自己需要處理的是.log文件所以在此加一個(gè)判斷path_read.append(temp_path) else:continue else: check_if_dir(file_path + ’/’ + temp_list_each) #loop traversalcheck_if_dir(path)#print(path_read)
實(shí)現(xiàn)思想就是把所有可執(zhí)行文件的路徑,通過(guò)字符串的拼接,完整的放進(jìn)一個(gè)list中,在后面的執(zhí)行步驟中依次提取進(jìn)行訪問(wèn)和操作。
由于自己拿到的數(shù)據(jù)集中,一個(gè)文件夾下要么全是文件夾,要么全是文件,所以在第一次寫這個(gè)函數(shù)時(shí),通過(guò)temp_list[0] 直接判斷l(xiāng)ist中第一個(gè)文件是不是文件。
所以自己第一次寫的代碼有一個(gè)很大的bug,就是當(dāng)一個(gè)文件夾下既有文件夾又有文件的情況下,會(huì)嘗試將一個(gè)文件夾按照文件讀取,報(bào)錯(cuò)。
第一次代碼如下:
import ospath = ’abc’path_read = [] #path_read saves all executable filesdef check_if_dir(file_path): temp_list = os.listdir(file_path) #put file name from file_path in temp_list if os.path.isfile(file_path + ’/’ + temp_list[0]): #此處直接判斷l(xiāng)ist中第一項(xiàng)是不是文件 for temp_list_each in temp_list: temp_path = file_path + ’/’ + temp_list_each if os.path.splitext(temp_path)[-1] == ’.log’:path_read.append(temp_path) else:continue else: for temp_list_each in temp_list: check_if_dir(file_path + ’/’ + temp_list_each) #loop traversalcheck_if_dir(path) #put all path in path_read#print(path_read)
以上這篇python讀取多層嵌套文件夾中的文件實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML在語(yǔ)音合成中的應(yīng)用2. jscript與vbscript 操作XML元素屬性的代碼3. 不要在HTML中濫用div4. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)5. .NET Framework各版本(.NET2.0 3.0 3.5 4.0)區(qū)別6. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過(guò)程和條件語(yǔ)句)7. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)8. XML入門的常見問(wèn)題(三)9. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)10. HTTP協(xié)議常用的請(qǐng)求頭和響應(yīng)頭響應(yīng)詳解說(shuō)明(學(xué)習(xí))
