1. 递归遍历目录
import os
def getall(path, treeshow):
filelist = os.listdir(path)
treeshow += " "
for filename in filelist:
#拼接绝对路径
filepath = os.path.join(path, filename)
if os.path.isdir(filepath):
print(treeshow,"目录",filename)
getall(filepath, treeshow)
else:
print(treeshow,"文件",filename)
getall(r"d:\python\test","")
2. 栈模拟递归遍历目录
也称为深度遍历
画图分析:
import os
def getAllDirDE(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)
if os.path.isdir(fileAbsPath):
#是目录就压栈
print("目录:", fileName)
stack.append(fileAbsPath)
else:
#打印普通文件
print("普通文件:", fileName)
getAllDirED(r"/Users/zhangjiao/PycharmProjects/teaching")
3. 队列模拟递归遍历目录
也被称为广度遍历
画图分析:
import os
import collections
def getAllDirQU(path):
queue = collections.deque()
#进队
queue.append(path)
while len(queue) != 0:
#出队数据
dirPath = queue.popleft()
#找出所有的文件
fileList = os.listdir(dirPath)
for fileName in fileList:
#绝对路径
fileAbsPath = os.path.join(dirPath, fileName)
#判断是否是目录,是目录就进队,不是就打印
if os.path.isdir(fileAbsPath):
print("目录:", fileName)
queue.append(fileAbsPath)
else:
print("普通文件:", fileName)
getAllDirQU(r"/Users/zhangjiao/PycharmProjects/teaching")