Python零基礎學習筆記(三十八)——遞迴方法、棧、佇列模擬遍歷目錄

我是王佳俊發表於2019-01-26

用遞迴方法遍歷目錄:

使用到os模組,所以要先引入os模組

處理檔案:

    核心是判斷檔案是否是目錄檔案,如果是目錄檔案就進行遞迴處理,直接將檔名列印出來

下面是檔案程式碼:

import os
def getAllDir(path, sp = " "):
    fileList = os.listdir(path)
    #處理每一個檔案
    sp += "    "
    for fileName in fileList:
        #判斷是否是路徑(用絕對路徑)
        absFliePath = os.path.join(path, fileName)
        if os.path.isdir(absFliePath):
            print(sp + "目錄:", fileName)
            #遞迴呼叫
            getAllDir(absFliePath, sp)
        else:
            print(sp + "普通檔案", fileName)
    return fileList
getAllDir(r"C:UsersAdministratorPycharmProjectsuntitledday011")

棧方法:

import os
def getAllDirDE(path):
    stack = []
    stack.append(path)
    #處理棧,當棧為空的時候結束迴圈
    while len(stack) != 0:
        dirPath = stack.pop()
        fileDir = os.listdir(dirPath)
        for fileName in fileDir:
            fileAbsPath = os.path.join(dirPath, fileName)
            if os.path.isdir(fileAbsPath):
                print("目錄:"+ fileName)
                stack.append(fileAbsPath)
            else:
                print("普通檔案:", fileName)
getAllDirDE(r"C:UsersAdministratorPycharmProjectsuntitledday011")

佇列方法:

import os
import collections
def getAllDir(path):
    queue = collections.deque()
    #進隊
    queue.append(path)
    while len(queue) != 0:
        dirPath = queue.popleft()
        fileList = os.listdir(dirPath)
        for fileName in fileList:
            fileAbsPath = os.path.join(dirPath, fileName)
            if os.path.isdir(fileAbsPath):
                print("目錄:"+fileName)
                queue.append(fileAbsPath)
            else:
                print("檔案:"+fileName)

getAllDir(r"C:UsersAdministratorPycharmProjectsuntitledday011")


相關文章