You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何基于文件路径列表生成指定格式的树形结构字典

路径列表转自定义嵌套字典实现方案

第三方库说明

目前没有完全匹配你自定义输出结构的现成第三方库,这类定制化结构转换的逻辑不复杂,自行手动实现即可,灵活度也更高。

手动实现思路

  • 先将所有文件路径按/拆分,去掉每个路径分段的前后空白字符
  • 初始化一个虚拟根目录节点,对应你要求的最外层空路径文件夹
  • 遍历每个文件路径,逐层匹配根节点下的子文件夹,不存在的文件夹就新建对应节点,直到遍历到路径的最后一级(文件)
  • 所有文件挂载完成后,递归计算每个文件夹节点的object_count,即该文件夹下所有文件的总数量
  • 补全所有节点的object_name、object_type、object_path属性即可

完整实现代码

import json

def build_file_tree(f_list):
    # 初始化根节点
    root = {
        "object_name": "",
        "object_type": "folder",
        "object_path": "",
        "object_count": 0,
        "object_list": []
    }
    
    for file_path in f_list:
        # 拆分路径并去除分段前后空格
        parts = [p.strip() for p in file_path.split("/")]
        current_node = root
        current_path = ""
        
        # 处理路径中的文件夹层级
        for i in range(len(parts) - 1):
            part = parts[i]
            current_path = f"{current_path}/{part}" if current_path else part
            # 查找当前层级是否已存在对应文件夹
            found_folder = None
            for child in current_node["object_list"]:
                if child["object_type"] == "folder" and child["object_name"] == part:
                    found_folder = child
                    break
            # 不存在则新建文件夹节点
            if not found_folder:
                found_folder = {
                    "object_name": part,
                    "object_type": "folder",
                    "object_path": current_path,
                    "object_count": 0,
                    "object_list": []
                }
                current_node["object_list"].append(found_folder)
            current_node = found_folder
        
        # 添加文件节点
        file_name = parts[-1]
        current_node["object_list"].append({
            "object_path": file_path,
            "object_name": file_name,
            "object_type": "file"
        })
    
    # 递归统计每个文件夹的文件总数
    def calculate_count(node):
        if node["object_type"] == "file":
            return 1
        total = 0
        for child in node["object_list"]:
            total += calculate_count(child)
        node["object_count"] = total
        return total
    
    calculate_count(root)
    return root

# 测试用例
f_list = [
  "folder1 /folder1.1/images/image1.png",
  "folder1 /folder1.1/images/image2.png",
  "folder1 /folder1.1/images/image5.png",
  "folder1 /folder1.3/Invoice_1.pdf",
  "folder1 /folder1.3/Invoice_2.pdf",
  "folder1 /folder1.3/Invoice_3.pdf",
  "folder1 /folder1.3/Invoice_4.pdf",
  "folder1 /folder1.3/Invoice_5.pdf"
]

result = build_file_tree(f_list)
# 输出格式化后的结果
print(json.dumps(result, indent=2, ensure_ascii=False))

运行上述代码即可得到你要求的嵌套字典结构。

内容的提问来源于stack exchange,提问作者Ramesh Ponnusamy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:54:01