递归遍历目录

递归遍历目录

代码如下:

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:\千峰')

猜你喜欢

转载自www.cnblogs.com/allwell/p/9986026.html