您的位置:首页 > 编程语言 > Python开发

Python目录遍历的三种方式

2017-07-30 19:40 567 查看
三种遍历方式很类似,但是写之前要搞清它们各自编写的思想,要知道栈、队列的特点,以及递归的特点。广度遍历和深度遍历的区别要掌握

1、递归遍历目录

import os

def getAllDirRE(path, sp = ""):
# 得到当前目录下所有的文件
filesList = os.listdir(path)
# print(fileList)

# 处理每一个文件
sp += "   "
for fileName in filesList:
# path\fileName
# 判断是否是路径(用绝对路径)
absPath = os.path.join(path, fileName)
if os.path.isdir(absPath):
print(sp + "目录:", fileName)
getAllDirRE(absPath, sp)
else:
print(sp + "普通文件:", fileName)
getAllDirRE(r"要遍历的目标文件夹的绝对路径")


2、栈模拟递归遍历目录(深度遍历)

import os

def getAllDirDe(path):
stack = []
stack.append(path)
# print(stack)
# 处理栈,当栈为空的时候结束循环
while len(stack) != 0:
# 从栈里取出数据
dirPath = stack.pop()
filesList = os.listdir(dirPath)
# print(dirPath)
print(filesList)
# 处理每一个文件,如果是普通文件则打印出来,
# 如果是目录则将该目录的地址压栈
for fileName in filesList:
fileAbsPath = os.path.join(dirPath, fileName)
if os.path.isdir(fileAbsPath):
# 是目录就压栈
print("目录:", fileName)
stack.append(fileAbsPath)
else:
# 打印普通文件
print("普通:",fileName)

getAllDirDe(r"要遍历的目标文件夹的绝对路径")


3、队列模拟递归遍历目录(广度遍历)

import os
import collections

def getAllDirQU(path):
queue = collections.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)
getAllDirQU(r"要遍历的目标文件夹的绝对路径")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: