Python零基础学习笔记(三十八)—— 递归方法、栈、队列模拟遍历目录
用递归方法遍历目录:
使用到os模块,所以要先引入os模块
处理文件:
核心是判断文件是否是目录文件,如果是目录文件就进行递归处理,直接将文件名打印出来
下面是文件代码:
import os
def getAllDir(path, sp = " "):
fileList = os.listdir(path)
#处理每一个文件
sp += " "
for fileName in fileList:
#判断是否是路径(用绝对路径)
absFliePath = os.path.join(path, fileName)
if os.path.isdir(absFliePath):
print(sp + "目录:", fileName)
#递归调用
getAllDir(absFliePath, sp)
else:
print(sp + "普通文件", fileName)
return fileList
getAllDir(r"C:\Users\Administrator\PycharmProjects\untitled\day011")
栈方法:
import os
def getAllDirDE(path):
stack = []
stack.append(path)
#处理栈,当栈为空的时候结束循环
while len(stack) != 0:
dirPath = stack.pop()
fileDir = os.listdir(dirPath)
for fileName in fileDir:
fileAbsPath = os.path.join(dirPath, fileName)
if os.path.isdir(fileAbsPath):
print("目录:"+ fileName)
stack.append(fileAbsPath)
else:
print("普通文件:", fileName)
getAllDirDE(r"C:\Users\Administrator\PycharmProjects\untitled\day011")
队列方法:
import os
import collections
def getAllDir(path):
queue = collections.deque()
#进队
queue.append(path)
while len(queue) != 0:
dirPath = queue.popleft()
fileList = os.listdir(dirPath)
for fileName in fileList:
fileAbsPath = os.path.join(dirPath, fileName)
if os.path.isdir(fileAbsPath):
print("目录:"+fileName)
queue.append(fileAbsPath)
else:
print("文件:"+fileName)
getAllDir(r"C:\Users\Administrator\PycharmProjects\untitled\day011")

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
-
上一篇
Python零基础学习笔记(三十七)—— 栈和队列
#模拟栈结构 stack = [] #压栈(向栈里面存数据) stack.append("A") print(stack) stack.append("B") stack.append("C") print(stack) #出栈(在栈里面取数据) res1 = stack.pop() print(res1) print(stack) res2 = stack.pop() print(res2) print(stack) res3 = stack.pop() print(res3) print(stack) #模拟队列 import collections #创建队列 queue = collections.deque() print(queue) #进队 queue.append("A") print(queue) queue.append("B") print(queue) #出队 res1 = queue.popleft() print(res1) print(queue) res2 = queue.popleft() print(res2) print(queue)
-
下一篇
PHP 7.3声称速度比PHP 5快3倍还多,值得更新了!
PHP 7.3声称速度比PHP 5快3倍还多,值得更新了! 作为PHP5的最后一个版本,也是目前使用最广泛的PHP版本,PHP 5.6始于公元2014年(不是1804年,嘿嘿),其第一个测试版PHP 5.6 alpha 1版于2014年1月发布。随机产生了第一个由国人(鸟哥,惠新宸)参与主研的性能大规模提升版本PHPNG(PHP next generation,下一代PHP),2015年基于PHPNG接着就产生PHP 7版本。PHP7带来了革命性的性能提高,其运行速率是5.6的两倍还高以及其他改善,比如64位支持、类型申明、运行时优化等。从2015年开始官方就一直推荐大家尽快升级到php7,虽然当时扩展支持还是很成问题。 根据最新的W3techs统计,目前PHP 7大概占了超过16.6%的PHP份额。 总体上PHP仍然拥有大约83%的网站服务器端开发语言的绝大多数比例。 根据PHP开发支持周期,到今年12月31日后,PHP 5.6不在有官方支持。所以现在只剩下半年时间你升级你的PHP到PHP7。此后PHP5的命运就会终结,而且就虫虫所致目前基本上绝大多数的框架和程序都已经完美的支持PH...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- 设置Eclipse缩进为4个空格,增强代码规范
- CentOS关闭SELinux安全模块
- Eclipse初始化配置,告别卡顿、闪退、编译时间过长
- Jdk安装(Linux,MacOS,Windows),包含三大操作系统的最全安装
- CentOS8编译安装MySQL8.0.19
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- SpringBoot2整合Thymeleaf,官方推荐html解决方案
- MySQL数据库在高并发下的优化方案
- SpringBoot2更换Tomcat为Jetty,小型站点的福音