欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【递归遍历02】栈模拟遍历目录(深度遍历)

程序员文章站 2022-05-03 20:05:03
...
import os


def getAllDir(path):
    stack = []
    stack.append(path)
    # 当栈为空的时候处理栈
    while len(stack) != 0:
        # 从栈里取数据
        dirpath = stack.pop()
        filelist = os.listdir(dirpath)
        # 处理文件
        for filename in filelist:
            fileAbsPath = os.path.join(dirpath, filename)
            print(fileAbsPath)
            if os.path.isdir(fileAbsPath):
                print('目录', filename, '入栈')
                stack.append(fileAbsPath)

            else:
                print('文件', filename)


path = r'D:\pypypy\high_learn'

getAllDir(path)

 

如果是目录就压入栈中,文件直接打印

在栈中的文件,先进的后处理,后进的先处理

 

相关标签: python之道