python遞迴遍歷資料夾裡面的所有檔案
阿新 • • 發佈:2018-12-12
import os path = "F:/new" #資料夾目錄 datas = [] def eachFile(filepath): fileNames = os.listdir(filepath) # 獲取當前路徑下的檔名,返回List for file in fileNames: newDir = filepath + '/' + file # 將檔案命加入到當前檔案路徑後面 # print(newDir) # if os.path.isdir(newDir): # 如果是資料夾 if os.path.isfile(newDir): # 如果是檔案 if os.path.splitext(newDir)[1] == ".txt": # 判斷是否是txt f = open(newDir) str = "" for line in f.readlines(): str = str + line # 讀檔案 datas.append(str) else: eachFile(newDir) #如果不是檔案,遞迴這個資料夾的路徑 if __name__ == "__main__": eachFile(path) print(datas)