递归遍历目录
import os
def getAllDirRe(path, sp = ""):
filesList = os.listdir(path)
sp += " "
for fileName in filesList:
fileAbsPath = os.path.join(path, fileName)
if os.path.isdir(fileAbsPath):
print(sp + "目录:" + fileName)
getAllDirRe(fileAbsPath, sp)
else:
print(sp + "普通文件:" + fileName)
path = r"D:\My Documents"
getAllDirRe(path)
栈模拟递归遍历目录(深度遍历)
import os
def getAllDirDE(path):
stack = []
stack.append(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)
path = r"D:\My Documents"
getAllDirDE(path)
队列模拟递归遍历目录(广度遍历)
import os
from collections import deque
def getAllDirQU(path):
queue = deque()
queue.append(path)
while len(queue) != 0:
dirPath = queue.popleft()
filesList = os.listdir(dirPath)
for fileName in filesList:
fileAbsPath = os.path.join(dirPath, fileName)
if os.path.isdir(fileAbsPath):
print("目录:" + fileName)
queue.append(fileAbsPath)
else:
print("普通文件:" + fileName)
path = r"D:\My Documents"
getAllDirQU(path)