首页 > 编程语言 >自动化之python读取目录结构转换为element-plus tree结构

自动化之python读取目录结构转换为element-plus tree结构

时间:2024-06-18 17:22:03浏览次数:15  
标签:python tree element start file child path data

def get_project_tree(start_path: str, original_path: str, tree_data:list):
    child_files = os.listdir(start_path)
    for child_file in child_files:
        if child_file in ['.gitignore', '.idea', 'venv', '__pycache__']:
            continue
        filepath = os.path.join(start_path, child_file)
        # 如果是目录则继续递归处理
        if os.path.isdir(filepath):
            dir_child = {
                "label": child_file,
                "children": []
            }
            if start_path != original_path:
                # 如果不等于,则说明当前已经处于其他的子层下,根据子层层级寻找child,并将数据存入
                calcu_now = start_path.split("\\")[len(original_path.split("\\")):]
                update_dict_value_by_path(tree_data, calcu_now, dir_child)
            else:
                tree_data.append(dir_child)
            get_project_tree(filepath, original_path, tree_data)
        # 解决根目录下可能存在文件
        elif start_path == original_path:
            if not child_file.endswith(".py"):
                continue
            final_child = {
                "label": child_file
            }
            tree_data.append(final_child)
        # 解决子目录下的文件写入对应子目录下
        elif start_path != original_path:
            if not child_file.endswith(".py"):
                continue
            # 如果不等于,则说明当前已经处于其他的子层下,根据子层层级寻找child,并将数据存入
            calcu_now = start_path.split("\\")[len(original_path.split("\\")):]
            final_child = {
                "label": child_file
            }
            update_dict_value_by_path(tree_data, calcu_now, final_child)
        else:
            raise AttributeError("存在未处理的情况")
        # return tree_data


def update_dict_value_by_path(tree_data, path, final_child, tree_tier=0):
    if isinstance(path, str):
        keys = path.split('.')
    elif isinstance(path, list):
        keys = path
    else:
        raise ValueError("不支持的路径类型")
    d = tree_data
    for child in d:
        try:
            if child["label"] != path[tree_tier]:
                # 不是要找的目录,则继续循环
                continue
        except IndexError:
            # 说明是找到了最后一层,当不做处理,继续执行
            continue
        # 已经找到了对应的目录,看是不是目标层级
        if len(path) == tree_tier + 1:
            child["children"].append(final_child)
        # 说明时找到了对应的层级目录,但是没到目标层级
        tree_tier += 1
        update_dict_value_by_path(child["children"], path, final_child, tree_tier)
    return tree_data


# 使用示例
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
tree_data = []
get_project_tree(base_dir, base_dir, tree_data)
print(tree_data)

执行结果:
image

标签:python,tree,element,start,file,child,path,data
From: https://www.cnblogs.com/T-Ajie/p/18254745

相关文章

  • Python - Arrays and Numpy Arrays
    Mostprogramminglanguagesprovideadatastructurecalledarrays.InPython,arrayisapackageanditisdifferentfrom“core”pythonlists.    Thesyntaxforcreatinganarray. DifferencesbetweenNumpyArraysandArrays PythonPredefi......
  • k8s的python客户端库--kubernetes
    简介Kubernetes是什么Kubernetes是一个全新的基于容器技术的分布式架构解决方案,是Google开源的一个容器集群管理系统,Kubernetes简称K8S。Kubernetes是一个一站式的完备的分布式系统开发和支撑平台,更是一个开放平台,对现有的编程语言、编程框架、中间件没有任何侵入性。K......
  • python简单账表(包括联查)
    import clrclr.AddReference("System")clr.AddReference("Kingdee.BOS")clr.AddReference("Kingdee.BOS.Core")clr.AddReference("Kingdee.BOS.DataEntity")clr.AddReference("Kingdee.BOS.App")clr.AddReference(&q......
  • 关于几种语言(c#,php,python,javascript)字符串的gzip压缩与解压的整理
    背景介绍因为一直在处理restfulAPI,给移动端提供的数据需要考虑流量问题,优先考虑就是压缩现有的字符串,然后再考虑业务逻辑方面的减少流量。鉴于找这些资料也花了不少时间,所以整理了这篇文章,留作纪念。参考网址PHP与C#的压缩与解压http://www.oschina.net/question/2265205_181......
  • python函数声明(参数/返回值注释)和三个双引号用法
     1#python的"""三个双引号两种用法:(1)多行注释(2)定义多行字符串2deff1(ham:42,eggs:int='spam')->"Nothingtoseehere":3print("函数注释",f1.__annotations__)#函数注释{'ham':42,'eggs':<cl......
  • (slam工具)6 python四元数转化旋转矩阵
       importnumpyasnpfromscipy.spatial.transformimportRotationasRimportpyprojfrompyprojimportProj,transform#0.0169380355232107080.58455146147157355-0.488705791564092830.64744060819180593-129342.747563395343469822.8668770161534369......
  • IPython 使用技巧整理
    IPython使用技巧整理IPython是一种强大的交互式Pythonshell,提供了许多增强功能,适合数据科学、机器学习和科学计算等多个领域。以下是一些常用的IPython使用技巧。目录基础功能魔法命令扩展和插件与JupyterNotebook的集成调试与错误处理性能优化基础功能1.自动......
  • 基于Java+SpringBoot+Vue+elementUI的学生宿舍管理平台的设计与开发
    第一章绪论1.1选题背景和意义1.2国内外学生宿舍管理平台现状第二章相关技术简介2.1开发工具介绍2.1.1IDEA2.1.2VSCode2.1.3Navicat2.1.4宝塔面板2.2关键技术介绍2.2.1Java2.2.2SpringBoot2.2.3Mybatis2.2.4Vue2.2.5MySQL2.2.6Redis2.2.7E......
  • 小于n的最大数 - 贪心算法及证明 - 附python实现
    一、问题描述?    给定一个整数n,并从1~9中给定若干个可以使用的数字,根据上述两个条件,得到每一位都为给定可使用数字的、最大的小于整数n的数。    例如,给定可以使用的数字为{2,3,8}三个数:    给定n=3589,输出3388;给定n=8234,输出8233;…… 二、解......
  • Python - Meta Class
    Aspartofmetaprogramming,ametaclassisoneofthemostimportantconceptsinPython.AClassinPythondefinesthefunctionalityofitsobjectsusingattributesandmethods.Incontrast,ametaclassdefinesthefunctionalityoftheclasses,whereast......