实现效果
思路及笔记
"""
@name : 实现tree命令
@author : huangshilong
@projectname : pythonfunction
"""
"""
知识点总结:
1、python中如何将文件夹路径作为实参输入到函数当中
以字符串的形式将路径输入即可,记得每一级路径之间用//连接
2、os模块的引入
什么是os模块
os模块提供了多数操作系统的功能接口函数。
我们将用到下面两个函数
os.path.isdir()判断是否为为文件夹
os.listdir() 生成文件夹的子文件列表
print(os.listdir("D:\\Python"))
['Python项目', '软件安装']
3\Python在递归时如何实现静态变量
在函数递归时,需要一个depth参数来记录每一层递归的缩进量
但是Python不支持静态变量的定义,不能在函数内定义。
我们可以将此变量作为参数传入
"""
# 引入os模块
import os
# dir参数是文件路径
def tree_ord(dir,depth):
#如果是母文件,则不用缩进和连接符直接输出
if depth == 0 :
print(dir)
for element in os.listdir(dir):
# 输出子文件夹
print(" | "*depth,"|----"+element)
# 更新到子文件夹的路径
path = dir +"//" +element
# 判断子文件夹是否为文件夹
if(os.path.isdir(path)):
# 如果是文件夹则递归输出,深度+1
tree_ord(path,depth+1)
tree_ord("C:\\test",0)