【发布时间】:2023-02-18 00:09:27
【问题描述】:
我正在尝试读取一个 json 文件,修改然后保存修改后的版本。 不幸的是,文件的内容没有被保存,而是在原始文件的末尾添加了另一个 json。
我的代码:
with open(os.environ.get("WORKSPACE")+"/test.json", 'r+') as test_file:
test = json.load(test_file)
test['COMPONENTS'] = "test components"
json.dump(test, test_file)
测试.json
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}
运行代码后
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}
预期结果:
{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}
请指出我做错了什么
我的环境 蟒蛇 3.10.9 macOS 12.3.1
我尝试使用 w+
Exception has occurred: JSONDecodeError
Expecting value: line 1 column 1 (char 0)
StopIteration: 0
During handling of the above exception, another exception occurred:
File "/test.py", line 20, in <module>
test = json.load(test_file)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
【问题讨论】: