【发布时间】:2021-05-31 05:00:40
【问题描述】:
我正在尝试做这样的事情,它同时使用读取、附加和写入。
with open("data.json", mode="a+") as file:
# 1.Reading old data
data = json.load(file)
# 2. Updating old data with new data
data.update(new_dict)
# 3.Writing into json file
json.dump(data,file,indent=4)
但它显示json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
【问题讨论】:
-
您在另一个末尾附加了一个 JSON 字符串,使磁盘文件无效。您应该以
r模式读取文件,然后以w模式重新打开以覆盖它。 -
我认为错误发生在
json.load时。检查data.json的内容。您似乎将 JSON 附加到文件中,而不是替换它,导致在代码运行一次后两个 JSON 一个接一个地出现在文件中,这会弄乱第二次调用。写之前用file.seek(0)回到开头。 -
是的,我想用 file.seek(0 ) 它给出了同样的错误。
标签: python json file file-handling