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í)行文件的路徑,通過字符串的拼接,完整的放進(jìn)一個(gè)list中,在后面的執(zhí)行步驟中依次提取進(jìn)行訪問和操作。
由于自己拿到的數(shù)據(jù)集中,一個(gè)文件夾下要么全是文件夾,要么全是文件,所以在第一次寫這個(gè)函數(shù)時(shí),通過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. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis2. Python 忽略文件名編碼的方法3. python 基于Appium控制多設(shè)備并行執(zhí)行4. android studio實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器(無bug)5. Java Media Framework 基礎(chǔ)教程6. 解決vue頁(yè)面刷新,數(shù)據(jù)丟失的問題7. python 實(shí)現(xiàn)圍棋游戲(純tkinter gui)8. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作9. 在Mac中配置Python虛擬環(huán)境過程解析10. Python趣味挑戰(zhàn)之用pygame實(shí)現(xiàn)簡(jiǎn)單的金幣旋轉(zhuǎn)效果
