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文件所以在此加一個判斷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)一個list中,在后面的執(zhí)行步驟中依次提取進(jìn)行訪問和操作。
由于自己拿到的數(shù)據(jù)集中,一個文件夾下要么全是文件夾,要么全是文件,所以在第一次寫這個函數(shù)時,通過temp_list[0] 直接判斷l(xiāng)ist中第一個文件是不是文件。
所以自己第一次寫的代碼有一個很大的bug,就是當(dāng)一個文件夾下既有文件夾又有文件的情況下,會嘗試將一個文件夾按照文件讀取,報(bào)錯。
第一次代碼如下:
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í)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. python中PyQuery庫用法分享3. python操作數(shù)據(jù)庫獲取結(jié)果之fetchone和fetchall的區(qū)別說明4. python 爬取嗶哩嗶哩up主信息和投稿視頻5. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)6. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺】7. 關(guān)于HTML5的img標(biāo)簽8. php5.6不能擴(kuò)展redis.so的解決方法9. ASP.NET MVC前臺動態(tài)添加文本框并在后臺使用FormCollection接收值10. CSS3實(shí)現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效
