Python3 - 遍历目录 Python3 递归 遍历目录 2017/09/14 通过三种方式遍历目录 – 递归、栈、队列 一、递归遍历目录 1234567891011121314import os # 导入os模块def getAllDir(path): # os.listdir 返回指定文件夹目录(列表形式) fileAll = os.listdir(path) # 获取path目录下的所有文件及子目录 for fileName in fileAll: # 遍历获取path目录下的所有文件及子目录 fileName即为目录名或文件名 # os.path.join 全路径的拼接 filePath = os.path.join(path, fileName) # 将path目录与目录名或文件名拼接起来, 以便下一步判断 # os.path.isdir 判断是否是目录 if os.path.isdir(filePath): print('文件夹:' + fileName) # 如果为目录, 打印输出目录 getAllDir(filePath, str) # 递归getAllDir()方法 直到目录下面的文件全部遍历出来 else: print('文件: ' + fileName) # 如果为文件, 打印输出文件getAllDir(path) 二、使用栈模拟递归遍历目录 123456789101112131415161718import os # 导入os模块def getALLDir(path): list1 = [] list1.append(path) while len(list1) != 0: # 开始从列表中取数据 dirPath = list1.pop() # 得到文件下边的所有文件路径 filesAll = os.listdir(dirPath) for filename in filesAll: # 路径拼接全路径 filePath = os.path.join(dirPath, filename) if os.path.isdir(filePath): # 是目录 list1.append(filePath) else: # 是文件 print('文件' + filename) 三. 使用队列模拟递归遍历目录 1234567891011121314151617181920212223242526import os # 导入os模块import collections # 导入collections模块def getAllDir(path): # 创建列表 # 使用collections.deque方法可以创建一个两端都可以操作的列表,也就是说我们可以在两端进行添加和删除 que = collections.deque() que.append(path) while len(que) != 0: # 得到文件路径 dirPath = que.popleft() # 获取该路径下边的文件和文件夹 filesPath = os.listdir(dirPath) for filename in filesPath: # 拼接全路径 filePath = os.path.join(dirPath, filename) if os.path.isdir(filePath): # 是目录 que.append(filePath) else: # 是文件 print('文件' + filename)
评论系统未开启,无法评论!