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

Python中json.dump生成的JSON文件二次运行无法解码求助

问题:Python读取JSON文件重复出现解码错误

我编写了如下Python代码:

import json

idref = "../Data/Resources/oids.json"

with open(idref,"w+") as file_ref:
    try:
        ref = json.load(file_ref)
    except json.decoder.JSONDecodeError as e:
        print("decode error: {}".format(e))
        ref = {"ids":[]}

    print(ref)
    for i in range(1600,1605,1):
        ref["ids"].append(i)
    json.dump(ref,file_ref,indent=4)

首次运行时(oids.json文件不存在),出现预期的decode error: Expecting value: line 1 column 1 (char 0)错误,生成的文件内容符合预期:

{
    "ids": [
        1600,
        1601,
        1602,
        1603,
        1604
    ]
}

但再次运行时,仍出现相同的解码错误,输出{'ids': []},无法读取已生成的文件。运行环境为Python 3.9.6、Mac OS Monterey 12.4。


问题原因与解决办法

核心原因

使用w+模式打开文件时,无论文件是否存在,都会直接清空原有内容,文件指针初始位于文件开头。第二次运行时,文件刚被打开就被清空,json.load读取空内容自然触发解码错误。

解决思路

分开处理文件的读取与写入逻辑,先尝试读取已有文件,再写入更新后的内容;或使用不会清空文件的模式配合指针调整。

修正后的代码(推荐方案)

import json
import os

idref = "../Data/Resources/oids.json"

# 先读取已有文件,不存在则初始化空结构
if os.path.exists(idref):
    with open(idref, "r") as file_ref:
        try:
            ref = json.load(file_ref)
        except json.decoder.JSONDecodeError as e:
            print("decode error: {}".format(e))
            ref = {"ids": []}
else:
    ref = {"ids": []}

print(ref)
for i in range(1600, 1605, 1):
    ref["ids"].append(i)

# 写入更新后的内容
with open(idref, "w") as file_ref:
    json.dump(ref, file_ref, indent=4)

单with块替代方案(逻辑稍复杂)

如果想在单个with块中完成操作,可使用a+模式配合指针调整:

import json

idref = "../Data/Resources/oids.json"

with open(idref, "a+") as file_ref:
    # 将指针移到文件开头准备读取
    file_ref.seek(0)
    try:
        ref = json.load(file_ref)
    except json.decoder.JSONDecodeError as e:
        print("decode error: {}".format(e))
        ref = {"ids": []}

    print(ref)
    for i in range(1600, 1605, 1):
        ref["ids"].append(i)
    
    # 移回开头并清空文件,再写入新内容
    file_ref.seek(0)
    file_ref.truncate()
    json.dump(ref, file_ref, indent=4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:03:26