import os,json
# HTML模板
html = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.2.6/css/layui.css" media="all">
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
<legend>基本树</legend>
</fieldset>
<div style="display: inline-block; width: auto; height: auto; padding: 10px; border: 1px solid #ddd; overflow: auto;">
<ul id="demo1"></ul>
</div>
</body>
<script src="https://www.layuicdn.com/layui-v2.4.5/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
layui.use(['tree', 'layer'], function(){
var layer = layui.layer, $ = layui.jquery;
layui.tree({
elem: '#demo1' //指定元素
,extend: 'myskin/style.css' //加载新皮肤
,skin: 'layer-ext-myskin' //一旦设定,所有弹层风格都采用此主题。
,target: '_blank' //是否新选项卡打开(比如节点返回href才有效)
,click: function(item){ //点击节点回调
//console.log(item);
CollapseLevel(3);setH();
}
,nodes: [ //节点
info_dict,
]
});
});
</script>
</html>
"""
def getDirectoryTree(folder):
'''
遍历本地目录返回字典树
:param folder:文件目录
:return:目录的字典
'''
dirtree = {'children':[]}
if os.path.isfile(folder):
return {'name':os.path.basename(folder),'href':os.path.abspath(folder)}
else:
dirtree['name'] = os.path.basename(folder)
for item in os.listdir(folder):
dirtree['spread'] = True
dirtree['children'].append(getDirectoryTree(os.path.join(folder,item)))
return dirtree
def getDirectoryTreeWithJson(folder):
'''
把字典树转换为字符串并返回
:param folder: 文件夹
:return:字符串
'''
return json.dumps(getDirectoryTree(folder))
info_dict = getDirectoryTreeWithJson(u"F:\\Desktop")
result = html.replace("info_dict",info_dict)
# print(info_dict)
# print(result) # 可以自行格式化
with open("rsp.html","w",encoding = "utf-8")as f:
f.write(result)
# 在线Json解码和格式化:https://www.5axxw.com/tools/v2/fjson.html
Python-遍历文件目录返回字典树【使用layui样式】
最新推荐文章于 2024-06-07 16:04:43 发布