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)
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?
{...original data...}{...appended data...}
– Anemometer