tree 命令 : 显示目录的树形结构
[root@localhost test]# ls
222 aaaa bbbb cccc.txt
[root@localhost test]# tree
.
├── 222
├── aaaa
│?? ├── 1111.txt
│?? └── qqqq
│?? └── fdfd
│?? └── jjjj
├── bbbb
└── cccc.txt
怎样用python 实现tree命令?
在python里面有一个 os库
os库有一个os.listdir() 方法,可以将目标路径下面所有的目录或者文件列出来
os库还有一个 os.path.isdir(),可以判断目标路径是否是文件夹
然后通过递归和循环就可以将所有目录都显示出来。
代码:
"""
@name : 03.函数的参数传递.py
@author : wangshenghu
@projectname: tlbb
@Date : 2022/2/27
"""
# 怎样用python实现tree命令
# os.listdir()列出当前文件夹下面有哪些文件
# 用递归做
import os
def pytree(path, depth=0):
if depth == 0:
print(path)
print("|")
# 循环输出路径下面所有的文件夹和文件
for file in os.listdir(path):
print("| " * depth, end="")
print("|----", file)
# os.path.isdir 判断需要绝对路径,用 + 拼接成绝对路径
files = path + "\\" + file
# 判断是否为文件夹,是的话递归调用自己
if os.path.isdir(files):
pytree(files, depth+1)
else:
# 是文件就直接输出出来
print("|----", file)
pytree("E:\\test")
效果: