多次运行Python程序时如何将dict数据正确写入JSON文件且不破坏格式
问题原因
你当前的报错是两个问题共同导致的:
- 写入代码存在变量名笔误:打开的文件句柄是
save_file,但调用write方法时用的是不存在的convert_file - 追加写入JSON对象时未添加分隔符:多次运行生成的JSON字符串直接拼接,导致整个文件内容既不符合标准JSON格式,也不符合行式JSON的逐行解析规则
方案1:使用行式JSON(JSON Lines)格式存储
该方案适配你现有的逐行读取逻辑,写入性能高,适合频繁追加写入的场景:
修正后的写入代码
import json d = data # 追加模式打开文件,每次写入后加换行符分隔不同JSON对象 with open('file.json', 'a', encoding='utf-8') as save_file: save_file.write(json.dumps(d, ensure_ascii=False) + '\n')
读取代码可保持原有逻辑,仅需增加空行过滤即可
import json with open('file.json', encoding='utf-8') as f: filedata = [json.loads(line) for line in f if line.strip()] print(filedata)
方案2:保持整个文件为标准JSON数组格式
如果需要整个文件是符合通用JSON规范的单个文件,可使用该方案:
写入逻辑:每次写入前读取现有数组,追加新元素后覆写文件
import json import os d = data file_path = 'file.json' # 读取已有数据 if os.path.exists(file_path) and os.path.getsize(file_path) > 0: with open(file_path, 'r', encoding='utf-8') as f: existing_data = json.load(f) else: existing_data = [] # 追加新数据 existing_data.append(d) # 覆写回文件 with open(file_path, 'w', encoding='utf-8') as f: json.dump(existing_data, f, ensure_ascii=False, indent=2)
读取逻辑直接加载整个文件即可
import json with open('file.json', 'r', encoding='utf-8') as f: filedata = json.load(f) print(filedata)
内容的提问来源于stack exchange,提问作者ItCameFr0mMars
相关产品推荐
相关产品推荐

