Python目录遍历的三种方式
2017-07-30 19:40
567 查看
三种遍历方式很类似,但是写之前要搞清它们各自编写的思想,要知道栈、队列的特点,以及递归的特点。广度遍历和深度遍历的区别要掌握
1、递归遍历目录
2、栈模拟递归遍历目录(深度遍历)
3、队列模拟递归遍历目录(广度遍历)
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"要遍历的目标文件夹的绝对路径")
相关文章推荐
- Python三种遍历文件目录的方法实例代码
- python列表和字符串的三种逆序遍历方式
- python中遍历list的三种方式
- python三种遍历目录的方法递归 栈 和队列
- python遍历的三种方式
- 【Python】三种遍历文件目录的方法
- python列表和字符串的三种逆序遍历方式
- 使用 Python 实现文件递归遍历的三种方式
- 【python中二叉树的实现】python中二叉树的创建、三种方式递归遍历和非递归遍历
- python For 循环 三种遍历方式
- Python遍历目录的多种方式
- python 入门学习---模块导入三种方式及中文凝视
- 递归方式遍历子目录下的子目录
- 二叉树三种遍历方式代码实现
- python文件操作之目录遍历实例分析
- 重温数据结构:二叉树的常见方法及三种遍历方式 Java 实现
- Python实现遍历目录下所有文件并写到文件中
- HashMap的三种遍历方式
- proc文件系统_每进程信息形成原理、目录遍历方式、位图查找
- python_urllib2下载网页的三种方式