json.dump()是否追加到文件? [英] Does json.dump() append to file?
问题描述
我在json.dump()中遇到了一些意外行为.我正在创建文件results
(空),然后在如下代码中使用它:
I'm getting some unexpected behavior with json.dump(). I'm creating a file results
(empty), and then using it in the code like this:
with open(results, 'r+') as fp:
temp = {}
try:
# file not empty, load existing dict, and add a key value to it
temp = json.load(fp)
temp[key] = value
except json.decoder.JSONDecodeError:
# file is empty, create a new dict
temp[key] = value
# write the dictionary back into file
json.dump(temp, fp)
如果以上引用执行一次,则可以正常工作.但是,如果我执行两次,则期望有一个带有两个键的字典:{key1: value1, key2: value2}
,但是我会得到两个字典:{key1: value1}{key2: value2}
.发生这种行为的原因可能是什么?
If the above quote executes once, it works fine. However, if I execute it twice, I'm expecting to have a single dictionary with two keys: {key1: value1, key2: value2}
, but I get instead two dictionaries: {key1: value1}{key2: value2}
. What could be the reason for such behavior?
推荐答案
在运行代码之前和之后查看输出文件,您应该看到发生了什么事.
Look at the output file before and after running the code, and you should see what's going on.
在json.dump
之前,文件对象指向文件的末尾.然后,您从该位置转储数据.
Right before the json.dump
, the file object points to the end of the file. You then dump data from this position.
如果您尝试先倒带文件,它应该从头开始覆盖数据:
If you try rewinding the file first, it should overwrite the data from the start:
fp.seek(0)
json.dump(temp, fp)
但是,如果写入的数据少于文件中已有的数据,则有可能使悬挂的数据超出第一个对象.因此,我建议您重组代码以通过两种操作读取和写入文件,并在写入时擦除文件.例如:
However, this could potentially leave dangling data beyond the first object, if it writes less data than is already in the file. I therefore suggest you restructure your code to read and write the file in two operations, wiping the file on the write. For example:
import json
filename = "foo"
print("Reading %s" % filename)
try:
with open(filename, "rt") as fp:
data = json.load(fp)
print("Data: %s" % data)
except IOError:
print("Could not read file, starting from scratch")
data = {}
# Add some data
data["key2"] = "value2"
print("Overwriting %s" % filename)
with open(filename, "wt") as fp:
json.dump(data, fp)
这篇关于json.dump()是否追加到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!