json.dump()で予期しない動作が発生しています。私は、ファイルresults
(空)を作成し、このようなコードでそれを使用しています:json.dump()はファイルに追加されますか?
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)
上記の引用は、一度実行した場合、それが正常に動作します。ただし、2回実行すると、2つのキー({key1: value1, key2: value2}
)を持つ1つの辞書が必要になりますが、代わりに2つの辞書:{key1: value1}{key2: value2}
が得られます。そのような行動の理由は何でしょうか?