使用栈来遍历目录
import os
def getdirstack(path):
# 创建一个栈
stack = []
# 先让根路径压栈
stack.append(path)
# 判断栈是否为空
while stack:
print(stack)
# 出栈
filepath = stack.pop()
# print(filepath)
# 列举指定目录下所有的目录及文件
fileList = os.listdir(filepath)
print(fileList)
for filename in fileList:
# 获取绝对路径
abspath = os.path.join(filepath,filename)
# 若是目录
if os.path.isdir(abspath):
print("目录:",filename)
stack.append(abspath)
# pass
else:
print("文件:",filename)
# pass
path = r"/PycharmProjects"
getdirstack(path)