栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python】遍历文件夹,生成zTree的Json目录树

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python】遍历文件夹,生成zTree的Json目录树

【Python】遍历文件夹,生成zTree的json目录树
  • 根据实际需要修改了代码,只保留了目录,排除了文件,通过os.path.isdir
  • 排除了~和.开头的目录,通过 os.path.basename(os.path.join(path, x))[0] not in [“~”, “.”]]
  • node2是json格式,通过json.dumps,ensure_ascii=False可正常显示中文路径
import os
import json
path = 'Q:\xxxxxx\SVN'


def path_to_dict(path):
    item = os.path.basename(path)
    d = {'name': item, 'children': [path_to_dict(os.path.join(path, x)) for x in os.listdir(path) if
                                    os.path.isdir(os.path.join(path, x)) and os.path.basename(os.path.join(path, x))[
                                        0] not in ["~", "."]]}
    return d


node = path_to_dict(path)
node2 = json.dumps(path_to_dict(path),ensure_ascii=False, indent=2)
print(node,node2)

运行结果:

#node
{'name': 'SVN', 'children': [{'name': '模板', 'children': [{'name': 'dir2', 'children': [{'name': 'dir3', 'children': []}]}]}]} 
#node2
{
  "name": "SVN",
  "children": [
    {
      "name": "模板",
      "children": [
        {
          "name": "dir2",
          "children": [
            {
              "name": "dir3",
              "children": []
            }
          ]
        }
      ]
    }
  ]
}

如果不需要排除文件,
参考:https://blog.csdn.net/weixin_34194359/article/details/94531403
stackoverflow参考链接

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022066.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号