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

解析嵌套JSON提取指定属性生成TXT及includes逐行输出问题

问题原因
  • 你直接调用str(includes_to_write)把列表转为了字符串,输出自然会保留["xxx", "yyy"]的数组格式,无法拆分换行
  • 原代码还存在其他可修复问题:
    • 遍历模块组件时写的v['components ']多了一个末尾空格,会触发KeyError报错
    • with open()上下文管理器会自动关闭文件,不需要额外调用f.close(),冗余代码可以删除
修复后代码
# 先确保你的components_path和path_to_includes变量末尾已经带了路径分隔符,或者用os.path.join拼接更稳妥
import os

for module_name, module_data in data.items():
    # 1、生成模块对应的txt文件
    module_file_path = os.path.join(components_path, f"{module_name}.txt")
    with open(module_file_path, 'w', encoding='utf-8') as f:
        for comp_name, comp_data in module_data["components"].items():
            f.write(f"{comp_data['path']}\n")
    
    # 2、生成每个组件对应的txt文件
    for comp_name, comp_data in module_data["components"].items():
        comp_file_path = os.path.join(path_to_includes, f"{comp_name}.txt")
        with open(comp_file_path, 'w', encoding='utf-8') as f:
            # 遍历includes列表逐行写入即可实现每个元素占一行
            for include_item in comp_data["includes"]:
                f.write(f"{include_item}\n")
            # 也可以用更简洁的写法,性能更优:f.write('\n'.join(comp_data["includes"]))
补充说明
  • 如果你担心不同系统的换行符兼容问题,用'\n'.join(comp_data["includes"])一次性写入的方案适配性更好
  • 用os.path.join拼接路径可以避免Windows、Linux/macOS的路径分隔符差异问题,代码通用性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:06:04