实现目标
linux中tree命令可以查看目录树,但是有时候我们并不不能使用这个命令。有可能你没有安装或者你无法进入bash命令行
依赖条件
已经安装好python3.11 ,原则上其他版本也可以
实现代码
主代码
# -*- coding: utf-8 -*-
# __ author:Jack
# date: 2024-04-01
import os
PREFIX = ['└─ ', '├─ ']
INDENTION = ['│ ', ' '*4]
# path : 文件夹全路径
# flag : 是否为最后一个文件(夹),为true 代表最后一个文件(夹),初始值None未被使用
# relation : 每层文件夹的flag属性
def tree(path, flag=None, relation=[]):
#files = os.listdir(path)
files = [f for f in os.listdir(path) if not f.startswith(".")]
files.sort(reverse=True)
yield ''.join(['' if flag is None else PREFIX[not flag],os.path.basename(path),'\n'])
if flag is not None:
relation.append(flag)
for i in files:
if i.startswith(".") or i.startswith("__"):
continue
for j in relation:
yield INDENTION[j]
tempPath = os.path.join(path,i)
if not os.path.isdir(tempPath):
yield ''.join([PREFIX[i!=files[-1]], i, '\n'])
else:
for i in tree(tempPath,i==files[-1],relation[:]):
print(i,end='')
HOME_DIR="/home/app"
if __name__=='__main__':
for i in tree(HOME_DIR):
print(i,end='')
AI 代码解读
输出样例
app ├─ test.ipynb ├─ source │ └─ info.json ├─ requirements.txt ├─ models │ └─ info.json ├─ datasets │ ├─ D202211002 │ │ ├─ target │ │ │ ├─ test.xlsx │ │ │ └─ 17Mxx.zip │ │ └─ src │ │ ├─ test.xlsx │ │ └─ test-1.jpg │ └─ D202211001 │ ├─ tag │ │ └─ test-1.jpg │ └─ original │ ├─ xx1.png │ ├─ roi.jpg │ ├─ readme │ ├─ 2.jpg │ └─ 1.89.gif └─ README.md
AI 代码解读