python中用栈的方式模拟递归遍历目录

#用栈的方式模拟递归遍历目录
import os
def getAllDirDE(path):
stack=[]#定义空栈
stack.sppend(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:\f\Python\pycharm")
posted @ 2019-02-27 14:52  飞飞阿  阅读(169)  评论(0编辑  收藏  举报