鱼C论坛

 找回密码
 立即注册
查看: 1767|回复: 3

[技术交流] 遍历目录(递归遍历,栈深度遍历,队列广度遍历)

[复制链接]
发表于 2019-2-27 14:35:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Stubborn 于 2019-4-3 20:50 编辑

递归遍历:
  1. import os
  2. def search_file(start_dir, sp=""):
  3.     os.chdir(start_dir)
  4.     sp += "   "
  5.     for each_file in os.listdir(os.curdir):
  6.         if os.path.isdir(each_file):
  7.             print(sp+"目录:"+os.getcwd() + os.sep + each_file)
  8.             search_file(each_file, sp)  
  9.             os.chdir(os.pardir)  
  10.         else:
  11.             print(sp+"文件:"+os.getcwd() + os.sep + each_file)

  12. start_dir = r"C:\Users\Administrator\Desktop"
  13. search_file(start_dir)
复制代码


栈深度遍历(先进后出),遍历目录不懂👇提问
  1. import os

  2. def get_all_dir_deep(path):
  3.     stack = []
  4.     stack.append(path)
  5.     while len(stack) !=0:
  6.         dirpath = stack.pop()
  7.         fileslist = os.listdir(dirpath)
  8.         for filename in fileslist:
  9.             fileabspath = os.path.join(dirpath,filename)
  10.             if os.path.isdir(fileabspath):
  11.                 print("目录:",filename)
  12.                 stack.append(fileabspath)
  13.             else:
  14.                 print("普通文件:",filename)

  15. path = "/Users/sstubborn/Desktop"
  16. get_all_dir_deep(path)
复制代码


队列广度遍历,先进先出
  1. import os
  2. import collections

  3. def get_all_dir_queue(path):
  4.     queue = collections.deque() #建队列
  5.     queue.append(path)

  6.     #处理队列,当队列为空结束循环
  7.     while len(queue) !=0:
  8.         dirpath = queue.popleft()
  9.         fileslist = os.listdir(dirpath)

  10.         for filename in fileslist:
  11.             fileabspath = os.path.join(dirpath,filename)
  12.             if os.path.isdir(fileabspath):
  13.                 print("目录:",filename)
  14.                 queue.append(fileabspath)
  15.             else:
  16.                 print("普通文件:",filename)

  17. path = "/Users/sstubborn/Desktop"
  18. get_all_dir_queue(path)
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-2-27 20:21:18 | 显示全部楼层
你这是啥不懂
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-2-27 22:56:02 | 显示全部楼层

三种模式打印历遍指定的文件目录而已大神有哪里不懂需要解释的  递归还有点问题,你也懂反正,看看哪里错了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-6-27 22:39:48 | 显示全部楼层
这个没啥问题吧,看着逻辑挺对的,运行结果也满足要求
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-27 18:54

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表