实现文件夹中文件的遍历输出
<p> </p>
<p>在之前的文章中:https://www.cnblogs.com/leiziv5/p/7411091.html,分享了基于python去递归查找文件中的文件。在后续的接触中,可以基于深度遍历和广度遍历来实现
</p>
<p>1.深度遍历实现
对应实现思路:
1.创建栈
2.增加路径
3.当栈不为空,处理栈的一个路径
4.遍历路径下面的每一项
5.遇到文件夹加入到栈中
6.知道栈中元素为空,退出
import os
path = "."
def GetAllDeep(path):
stack = []
stack.append(path)
# 处理栈,当栈为空时结束循环
while len(stack) != 0:
# 从栈里取出数据
DirPath = stack.pop()
# 目录下所有文件
num = 0
file_num = 0
FileList = os.listdir(DirPath)
# 循环处理每个文件
for FileName in FileList:
FileAbsPath = os.path.join(DirPath,FileName)
if os.path.isfile(FileAbsPath) == True:
print("是文件",FileAbsPath)
num += 1
else:
# print("是目录",FileAbsPath)
stack.append(FileAbsPath)
file_num += 1
print("当前文件数量:%s" % num, "当前文件夹数量%s" % file_num, "路径是:%s" % (FileAbsPath))


