溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python如何讀取多層嵌套文件夾中的文件

發(fā)布時間:2021-05-11 10:08:23 來源:億速云 閱讀:678 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)python如何讀取多層嵌套文件夾中的文件的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

python是什么意思

Python是一種跨平臺的、具有解釋性、編譯性、互動性和面向?qū)ο蟮哪_本語言,其最初的設(shè)計是用于編寫自動化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開發(fā)獨立的項目和大型項目。

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

python如何讀取多層嵌套文件夾中的文件

想到了遞歸函數(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文件所以在此加一個判斷
        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)

實現(xiàn)思想就是把所有可執(zhí)行文件的路徑,通過字符串的拼接,完整的放進(jìn)一個list中,在后面的執(zhí)行步驟中依次提取進(jìn)行訪問和操作。

由于自己拿到的數(shù)據(jù)集中,一個文件夾下要么全是文件夾,要么全是文件,所以在第一次寫這個函數(shù)時,通過temp_list[0] 直接判斷l(xiāng)ist中第一個文件是不是文件。

所以自己第一次寫的代碼有一個很大的bug,就是當(dāng)一個文件夾下既有文件夾又有文件的情況下,會嘗試將一個文件夾按照文件讀取,報錯。

第一次代碼如下:

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中第一項是不是文件
    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)

感謝各位的閱讀!關(guān)于“python如何讀取多層嵌套文件夾中的文件”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI