我在使用 json.dump() 时遇到一些意外行为。我正在创建一个文件 results(空),然后在代码中使用它,如下所示:
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}。这种行为的原因可能是什么?
请您参考如下方法:
查看运行代码前后的输出文件,您应该会看到发生了什么。
就在 json.dump 之前,文件对象指向文件的末尾。然后从该位置转储数据。
如果您先尝试倒回文件,它应该从头开始覆盖数据:
fp.seek(0)
json.dump(temp, fp)
但是,如果第一个对象写入的数据少于文件中已有的数据,这可能会在第一个对象之外留下悬空数据。因此,我建议您重组代码以在两个操作中读取和写入文件,并在写入时删除文件。例如:
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)
