本篇文章给大家谈谈python画树状图代treemap,以及python怎么画树状图,希望对各位有所帮助,不要忘了收藏本站喔。
Source code download: 本文相关源码
一、前言
在github浏览时,不时地能看到README页面中的项目文件目录树状图,将项目文件有序排列,如同Windows文件资源管理器左侧的列表。
它的好处是:赏心悦目、一目了然python简单图案代码。当项目有各种文件夹时,无需进入各个文件夹,即可快速了解:项目全部文件的位置分布。
于是,打算使用Python作为工具,参考网络资料,实现一下这种效果。
大致浏览并运行了CSDN中的相关Python实现代码,发现要么需要安装、导入第三方库,不太方便;要么实现的效果不太符合预期(如下图,在已出现转折的下方,仍有线条出现)。
二、预期效果
三、实现
1. 代码
参考资料:
(1)使用全局变量
#! /usr/bin/env python3
# -*- coding: UTF-8 -*-
"""显示目录树状图"""
import os
# site存储出现转折的层级号
site = []
def generate_file_tree_global(path, depth):
"""
递归打印文件目录树状图(使用全局变量)
:param path: 根目录路径
:param depth: 根目录、文件所在的层级号
:return: None
"""
global site
filenames_list = os.listdir(path)
if len(filenames_list) < 1:
return
# 本级目录最后一个文件名
last_filename = filenames_list[-1]
for item in filenames_list:
string_list = ["│ " for _ in range(depth - site.__len__())]
for s in site:
string_list.insert(s, " ")
if item != last_filename:
string_list.append("├── ")
else:
# 本级目录最后一个文件名,即为转折处
string_list.append("└── ")
# 添加当前出现转折的层级号
site.append(depth)
print("".join(string_list) + item)
new_path = path + '/' + item
if os.path.isdir(new_path):
generate_file_tree_global(new_path, depth + 1)
if item == last_filename:
# 结束本级目录搜索时,回收(移除)当前的转折层级号
site.pop()
if __name__ == '__main__':
# root_path = input("请输入根目录路径:")
root_path = "../../"
print(os.path.abspath(root_path))
generate_file_tree_global(root_path, depth=0)
(2)使用局部变量
#! /usr/bin/env python3
# -*- coding: UTF-8 -*-
"""显示目录树状图"""
import os
def generate_file_tree_local(path: str, depth: int, site: list):
"""
递归打印文件目录树状图(使用局部变量)
:param path: 根目录路径
:param depth: 根目录、文件所在的层级号
:param site: 存储出现转折的层级号
:return: None
"""
void_num = 0
filenames_list = os.listdir(path)
for item in filenames_list:
string_list = ["│ " for _ in range(depth - void_num - len(site))]
for s in site:
string_list.insert(s, " ")
if item != filenames_list[-1]:
string_list.append("├── ")
else:
# 本级目录最后一个文件:转折处
string_list.append("└── ")
void_num += 1
# 添加当前已出现转折的层级数
site.append(depth)
print("".join(string_list) + item)
new_item = path + '/' + item
if os.path.isdir(new_item):
generate_file_tree_local(new_item, depth + 1, site)
if item == filenames_list[-1]:
void_num -= 1
# 移除当前已出现转折的层级数
site.pop()
if __name__ == '__main__':
# root_path = input("请输入根目录路径:")
root_path = "../../../"
print(os.path.abspath(root_path))
generate_file_tree_local(root_path, depth=0, site=[])
- 上述代码中的“site”变量,类似于数据结构中的栈,先进后出、后进先出。
2. 实现效果
到此,预期效果基本实现了。
除此之外,还可以添加“颜色”效果,比如文件夹的名称均为蓝色,或某些特定文件类型(文件名、路径,甚至是不同层级等)的文件名称换上对应颜色……
可以参考:
结语
虽然现在完成后,感觉这个目录树状图还是挺简单的,但是解决“转折处下方的线条多余显示”问题,也费了半天功夫去想,才想出解决办法:用列表存储转折的层级号,又忽然意识到这好像有栈的影子。
数据结构并非全然高高在上,还是挺贴近生活的~~