1. 程式人生 > >遞迴遍歷目錄

遞迴遍歷目錄

遞迴遍歷目錄

程式碼如下:

import os

def getAllDirDE(path):
    stack =[]
    stack.append(path)

    #處理棧,當棧為空時結束迴圈
    while len(stack):
        #從棧裡取資料
        dirPath = stack.pop()
        #目錄下的所有檔案
        filesList = os.listdir(dirPath)
        #處理每一個檔案,如果是目錄,則將該目錄的地址壓棧,如果是普通檔案,則列印
        for filename in
filesList: fileAbsPath = os.path.join(dirPath, filename) if os.path.isdir(fileAbsPath): #是目錄就壓棧 stack.append(fileAbsPath) print("目錄"+filename) else: #列印普通檔案 print("普通檔案" + filename) getAllDirDE(r
'E:\千峰')

棧模擬遞迴遍歷目錄

程式碼如下:

import os

def getAllDirDE(path):
    stack =[]
    stack.append(path)

    #處理棧,當棧為空時結束迴圈
    while len(stack):
        #從棧裡取資料
        dirPath = stack.pop()
        #目錄下的所有檔案
        filesList = os.listdir(dirPath)
        #處理每一個檔案,如果是目錄,則將該目錄的地址壓棧,如果是普通檔案,則列印
        for
filename in filesList: fileAbsPath = os.path.join(dirPath, filename) if os.path.isdir(fileAbsPath): #是目錄就壓棧 stack.append(fileAbsPath) print("目錄"+filename) else: #列印普通檔案 print("普通檔案" + filename) getAllDirDE(r'E:\千峰')

佇列模擬遞迴遍歷目錄

程式碼如下:

import os
import collections

def getAllDirQU(path):
    queue = collections.deque()
    #進隊
    queue.append(path)
    while len(queue) !=0:
        #出隊資料
        dirPath = queue.popleft()
        filesList = os.listdir(dirPath)
        for fileName in filesList:
            #絕對路徑
            fileAbsPath = os.path.join(dirPath,fileName)
            #判斷是否是目錄,是就進隊,不是就列印
            if os.path.isdir(fileAbsPath):
                print("目錄" + fileName)
                queue.append(fileAbsPath)
            else:
                print("普通檔案" + fileName)
getAllDirQU(r'E:\千峰')