如何在Python循环中将多个扁平JSON文件追加到单个CSV文件
Python 循环生成JSON并追加到单个文件
你要实现的是每行一个JSON对象的格式(即JSON Lines),虽然你提到存为.csv,但这种格式用.jsonl后缀更规范,当然也可以直接用.csv后缀。以下是具体实现方法:
方法1:循环生成JSON数据并直接追加
如果是在循环中实时生成扁平化JSON对象,直接写入目标文件即可:
import json # 打开目标文件,用追加模式,指定编码避免乱码 with open('output.jsonl', 'a', encoding='utf-8') as out_file: # 示例循环,实际替换成你的业务生成逻辑 for item in your_data_source: # 模拟生成扁平化JSON数据(替换为你的实际生成代码) json_data = { "name": item["name"], "age": item["age"], "married": item["married"], "divorced": item["divorced"], "children": item["children"], "pets": item["pets"], "cars": item["cars"] } # 将JSON对象转为字符串,保留非ASCII字符 json_str = json.dumps(json_data, ensure_ascii=False) # 写入文件并换行,保证每行一个JSON out_file.write(json_str + '\n')
方法2:循环读取已有JSON文件并追加
如果是循环处理已生成的扁平化JSON文件,再追加到目标文件:
import json import os # 存放单个JSON文件的目录 json_files_dir = "./your_json_files/" # 打开目标文件,追加模式 with open('output.jsonl', 'a', encoding='utf-8') as out_file: # 遍历目录下所有JSON文件 for filename in os.listdir(json_files_dir): if not filename.endswith('.json'): continue file_path = os.path.join(json_files_dir, filename) # 读取单个JSON文件内容 with open(file_path, 'r', encoding='utf-8') as in_file: json_data = json.load(in_file) json_str = json.dumps(json_data, ensure_ascii=False) out_file.write(json_str + '\n')
关键注意事项
- 目标文件用
'a'模式打开,确保每次写入都是追加而非覆盖原有内容 json.dumps()加ensure_ascii=False,避免中文等非ASCII字符被转义成Unicode编码- 每行结尾必须加
\n,保证每个JSON对象单独占一行,匹配你需要的格式 - 尽量在循环外打开目标文件,减少文件打开/关闭的IO开销,提升运行效率
内容的提问来源于stack exchange,提问作者sylar_80
相关产品推荐
相关产品推荐

