我在使用 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)