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

Python3读取JSON文件修改后写入异常问题排查

问题原因及解决办法

为什么r+模式会出现追加内容的情况

用r+模式打开文件时,文件指针初始在开头,执行json.load(test_file)后,指针会移动到文件末尾。此时调用json.dump(test, test_file),新内容会从当前指针位置(原文件末尾)开始写入,最终变成追加而非覆盖。

为什么w+模式会触发JSONDecodeError

w+模式打开文件时,会先清空原文件的所有内容,此时文件是空的,json.load(test_file)读取空文件自然会抛出解析错误。

正确的处理方式

方式一:重置指针并截断文件

读取内容后,将文件指针移回开头,截断清除原内容后再写入新数据:

import os
import json

with open(os.environ.get("WORKSPACE")+"/test.json", 'r+') as test_file:
    test = json.load(test_file)
    test['COMPONENTS'] = "test components"
    # 将文件指针移回开头
    test_file.seek(0)
    # 截断文件,清除当前指针后的所有内容
    test_file.truncate()
    json.dump(test, test_file)

方式二:分开使用读、写模式

先以只读模式读取内容,关闭文件后再以写入模式打开覆盖原内容,逻辑更清晰:

import os
import json

file_path = os.environ.get("WORKSPACE")+"/test.json"
# 只读模式读取数据
with open(file_path, 'r') as test_file:
    test = json.load(test_file)

test['COMPONENTS'] = "test components"

# 写入模式打开(自动清空原文件)并写入新内容
with open(file_path, 'w') as test_file:
    json.dump(test, test_file)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:22:07