python讀取多層嵌套文件夾中的文件實(shí)例
由于工作安排,需要讀取多層文件夾下嵌套的文件,文件夾的結(jié)構(gòu)如下圖所示:

想到了遞歸函數(shù),使用python的os.path.isfile方法判斷當(dāng)前是不是可執(zhí)行文件,如果不是再用os.listdir方法將子目錄循環(huán)判斷。
代碼如下
import os
path = 'abc'
path_read = [] #path_read saves all executable files
def 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 traversal
check_if_dir(path)
#print(path_read)
實(shí)現(xiàn)思想就是把所有可執(zhí)行文件的路徑,通過(guò)字符串的拼接,完整的放進(jìn)一個(gè)list中,在后面的執(zhí)行步驟中依次提取進(jìn)行訪問(wèn)和操作。
由于自己拿到的數(shù)據(jù)集中,一個(gè)文件夾下要么全是文件夾,要么全是文件,所以在第一次寫(xiě)這個(gè)函數(shù)時(shí),通過(guò)temp_list[0] 直接判斷l(xiāng)ist中第一個(gè)文件是不是文件。
所以自己第一次寫(xiě)的代碼有一個(gè)很大的bug,就是當(dāng)一個(gè)文件夾下既有文件夾又有文件的情況下,會(huì)嘗試將一個(gè)文件夾按照文件讀取,報(bào)錯(cuò)。
第一次代碼如下:
import os
path = 'abc'
path_read = [] #path_read saves all executable files
def 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 traversal
check_if_dir(path) #put all path in path_read
#print(path_read)
以上這篇python讀取多層嵌套文件夾中的文件實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python操作手機(jī)app的實(shí)現(xiàn)步驟
本文主要介紹了python操作手機(jī)app的實(shí)現(xiàn)步驟,本文將結(jié)合實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07
一文教會(huì)你用Python3獲取網(wǎng)頁(yè)源代碼
學(xué)了python后,之前一些我們常用的方法,也可以換一種思路用python中的知識(shí)來(lái)解決,下面這篇文章主要給大家介紹了關(guān)于如何使用Python3獲取網(wǎng)頁(yè)源代碼的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06
python實(shí)現(xiàn)單張圖像拼接與批量圖片拼接
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)單張圖像拼接與批量圖片拼接,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
一篇文章帶你了解Python之Selenium自動(dòng)化爬蟲(chóng)
這篇文章主要為大家詳細(xì)介紹了Python之Selenium自動(dòng)化爬蟲(chóng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-01-01
將Python中的數(shù)據(jù)存儲(chǔ)到系統(tǒng)本地的簡(jiǎn)單方法
這篇文章主要介紹了將Python中的數(shù)據(jù)存儲(chǔ)到系統(tǒng)本地的簡(jiǎn)單方法,主要使用了pickle模塊,需要的朋友可以參考下2015-04-04
python程序文件擴(kuò)展名知識(shí)點(diǎn)詳解
在本篇文章里小編給大家整理的是關(guān)于python程序文件擴(kuò)展名知識(shí)點(diǎn)詳解內(nèi)容,需要的朋友們學(xué)習(xí)參考下。2020-02-02

