递归、栈和队列遍历

递归遍历

import os

def getAllDir(path, sp = ""):
    filesList = os.listdir(path)    # 得到当前目录下所有的文件
    sp += "    "
    for fileName in filesList:    # 处理每一个文件
        fileAbsPath = os.path.join(path, fileName)
        if os.path.isdir(fileAbsPath):    # 判断是否是路径
            print(sp, "目录:", fileName)
            getAllDir(fileAbsPath, sp)
        else:
            print(sp, "文件:", fileName)

getAllDir(r"C:\Users\xlg\Desktop\Python-1704\day09\temp\dir")
    

栈遍历(深度遍历)

import os

def getAllDirDE(path):
    stack = []
    stack.append(path)    # 压栈
    while len(stack) != 0:    #处理栈,当栈为空循环结束
        dirPath = stack.pop()
        filesList = os.listdir(dirPath)
        for fileName in filesList:    #处理每一个文件:普通文件打印,目录继续压栈
            fileAbsPath = os.path.join(dirPath, fileName)
            if os.path.isdir(fileAbsPath):
                print("目录:", fileName)
                stack.append(fileAbsPath)
            else:
                print("普通文件:", fileName)

getAllDirDE(r"D:\文档(Documents)")

队列遍历(广度遍历)

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"D:\文档(Documents)")    

猜你喜欢

转载自blog.csdn.net/u010378984/article/details/82905013
今日推荐