Python-遍历文件目录返回字典树【使用layui样式】

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

https://ed-service.com/
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值