gpt4 book ai didi

Python 无法加载由 json.dump 创建的 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 14:51:59 28 4
gpt4 key购买 nike

这似乎是一个非常简单的问题,我正在尝试读取 JSON 文件并修改一些字段。

with open("example.json", "r+") as f:
data = json.load(f)
# perform modifications to data
f.truncate(0)
json.dump(data, f)

它在我第一次手动创建 JSON 文件并存储正确的 JSON 文件时工作,但在我第二次运行相同的脚本时它给了我这个错误:

ValueError: No JSON object could be decoded

这是为什么呢?令我惊讶的是 json 模块无法解析模块本身创建的文件。

最佳答案

根据您提供的代码以及您尝试执行的操作(将文件光标返回到文件开头),您实际上并没有使用 f.truncate 执行此操作。您实际上是在截断您的文件。即完全清除文件。

根据 truncate 方法的帮助:

truncate(...)
truncate([size]) -> None. Truncate the file to at most size bytes.

Size defaults to the current file position, as returned by tell().

将光标返回到文件开头的实际操作是使用 seek

寻求帮助:

seek(...)
seek(offset[, whence]) -> None. Move to new file position.

因此,明确地说,要回到文件的开头,您需要 f.seek(0)

为了提供正在发生的事情的例子。以下是截断时发生的情况:

文件中有内容:

>>> with open('v.txt') as f:
... res = f.read()
...
>>> print(res)
1
2
3
4

调用 truncate 并看到该文件现在为空:

>>> with open('v.txt', 'r+') as f:
... f.truncate(0)
...
0
>>> with open('v.txt', 'r') as f:
... res = f.read()
...
>>> print(res)

>>>

使用 f.seek(0):

>>> with open('v.txt') as f:
... print(f.read())
... print(f.read())
... f.seek(0)
... print(f.read())
...
1
2
3
4



0
1
2
3
4


>>>

第一个输出之间的长间隙显示光标位于文件末尾。然后我们调用 f.seek(0)(0 输出来自 f.seek(0) 调用)并输出我们的 f.read()

关于Python 无法加载由 json.dump 创建的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155490/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com