Hello!我是”小恒不会java“
思考
今天突然看到某文里面:检查目录文件。引发了我的思考:首先应该看看目录树,检查一下
命令行
如何检查?我的电脑系统是win11,最简单的就是自带的文件系统功能
还有就是命令行工具:tree
命令(Windows和部分Linux发行版中自带)可以在终端中直接输出当前目录及其子目录的层级结构。不过看了看一些大项目的目录结构,根本不够看(太长了)
python 实现UI可视化
利用ttk
模块中的Treeview
控件展示指定目录及其子目录下的文件和子目录结构
代码
import os
import tkinter as tk
from tkinter import ttk
def populate_tree(tree, node):
if tree.set(node, "type") != "directory":
return
path = tree.set(node, "fullpath")
tree.delete(*tree.get_children(node))
for p in os.listdir(path):
p = os.path.join(path, p)
ptype = "file" if os.path.isfile(p) else "directory"
fname = os.path.split(p)[1]
oid = tree.insert(node, "end", text=fname, values=[p, ptype])
if ptype == "directory":
tree.insert(oid, "end", text="dummy")
tree.item(oid, text=fname)
def update_tree(event):
tree = event.widget
populate_tree(tree, tree.focus())
def create_root(path, tree):
root_node = tree.insert("", "end", text=path, values=[path, "directory"])
populate_tree(tree, root_node)
def main():
root = tk.Tk()
root.title("文件树可视化")
tree = ttk.Treeview(root, columns=("fullpath", "type"))
tree.heading("#0", text="文件结构(取决于该脚本文件层次)")
tree.column("#0", minwidth=0, width=200)
tree.bind("<<TreeviewOpen>>", update_tree)
tree.pack(fill=tk.BOTH, expand=True)
path = os.path.abspath(os.path.dirname(__file__))
create_root(path, tree)
root.mainloop()
if __name__ == "__main__":
main()
再次思考:能不能生成节点关系图
思路:
python将目录树导出为DOT文件以便用python脚本实现Graphviz渲染生成图片png或者svg
导出dot文件
实现导出
已经导出,在WPS里打开,足足150w+的字数
导出代码
import os
from anytree import Node
from anytree.exporter import DotExporter
def build_file_tree(directory):
root = Node(directory)
for dirpath, dirs, files in os.walk(directory):
current_node = Node(os.path.basename(dirpath), parent=root)
for file in files:
Node(file, parent=current_node)
print("第一步:Building file tree...")
return root
def main():
directory = "C:" # 替换为你要可视化的目录路径
root_node = build_file_tree(directory)
# 将文件树导出为DOT文件
DotExporter(root_node).to_dotfile("file_tree.dot")
print("第二步:Building file tree...")
if __name__ == "__main__":
main()
print("文件树已生成,请在当前目录下打开file_tree.dot文件")
将dot文件渲染成图片
环境配置
pip安装graphviz
库的Python接口,再安装Graphviz工具。最后配置环境变量
参考官方文档:User Guide — graphviz 0.20.3 documentation
python脚本实现图形渲染
代码
from graphviz import Source
with open("C:\\Users\\李恒\\Desktop\\file_tree.dot", "r", encoding="utf-8") as f:
dot_source = f.read()
source = Source(dot_source)
source.render("graph", format="png")
标签:node,__,文件目录,tree,可视化,file,path,root
From: https://blog.csdn.net/2302_81578551/article/details/136995393