1. 程式人生 > >Python遞歸實現遍歷目錄

Python遞歸實現遍歷目錄

遞歸 內容 imp join light sdi def 是否 tdi

import os

filePath = "/Users/busensei/wzy/filePath/"


def read(filePath, n):
    it = os.listdir(filePath)  # 打開文件夾
    for el in it:
        #  拿到路徑
        fp = os.path.join(filePath, el)  # 獲取到絕對路徑
        if os.path.isdir(fp):  # 判斷是否是文件夾
            print("\t" * n, el)
            read(fp, n + 1)  # 又是文件夾. 繼續讀取內部的內容 遞歸入口
        else:
            print("\t" * n, el)  # 遞歸出口


read(filePath, 0)

Python遞歸實現遍歷目錄