【递归遍历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)
如果是目录就压入栈中,文件直接打印
在栈中的文件,先进的后处理,后进的先处理