解析嵌套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
相关产品推荐
相关产品推荐

