遍历目录文件的几种写法
整理为方便日后学习用到。
1. 简单递归
import os
def getAllDir(path, sp=""):
sp += " "
filesList = os.listdir(path)
# print(filesList)
for fileName in filesList:
fileAbsPath = os.path.join(path, fileName)
if os.path.isdir(fileAbsPath):
print(sp + "目录", fileName)
getAllDir(fileAbsPath, sp)
else:
print(sp + "普通文件", fileName )
getAllDir(r"E:\file\python3")
2. 栈模拟(深度遍历)
定义栈 :stack = []
入栈 : stack.append()
出栈 : stack.pop()
import os
def getAllDirStack(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):
stack.append(fileAbsPath)
print("目录"+ fileName)
else:
print("普通文件", fileName )
getAllDirStack(r"E:\file\python3")
3. 队列模拟(广度遍历)
定义空队列:queue = collections.deque()
入队:queue.append()
出队:queue.popleft()
import os
import collections
def getAllDirQueue(path):
queue = []
queue.append(path)
while len(queue) != 0:
dirPath = queue.popleft()
filesDir = os.listdir(dirPath)
for fileName in filesDir:
fileAbsPath = os.path.join(dirPath, fileName)
if os.path.isdir(fileAbsPath):
print("目录"+fileName)
queue.append(fileAbsPath)
else:
print("普通文件"+fileName)
getAllDirQueue(r"E:\file\python3")