Reputation: 1059
So I have a file python_dictionary.json
which contains a dictionary which I want to append to without having to open each time. Let's say that python_dictionary.json
contains only:
{
key1: value`
}
and I want to add
new_dictionary=
{
key2:value2
}
Right now I am doing:
with open('python_dictionary.json','a') as file:
file.write(json.dumps(new_dictionary,indent=4))
This creates a dictionary as:
{
key1:value1
}
{
key2:value2
}
which is obviously not a real dictionary.
I am aware of this: Add values to existing json file without rewriting it
but this deals with adding a single entry, I want to do a json.dumps
Upvotes: 9
Views: 33462
Reputation: 1450
When the 'r+' or 'a' option does not work properly, you can do the following:
with open('python_dictionary.json','r') as f:
dic = json.load(f)
dic.update(new_dictionary)
with open('python_dictionary.json','w') as f:
json.dump(dic, f)
The first part read the existing dictionary. Then you update the dictionary with the new dictionary. Finally, you rewriting the whole updated dictionary.
Upvotes: 1
Reputation: 461
Sounds like you want to load a dictionary from json, add new key values and write it back. If that's the case, you can do this:
with open('python_dictionary.json','r+') as f:
dic = json.load(f)
dic.update(new_dictionary)
json.dump(dic, f)
(mode is 'r+'
for reading and writing, not appending because you're re-writing the entire file)
If you want to do the append thing, along with json.dumps, I guess you'd have to remove the first {
from the json.dumps string before appending. Something like:
with open('python_dictionary.json','a') as f:
str = json.dumps(new_dictionary).replace('{', ',', 1)
f.seek(-2,2)
f.write(str)
Upvotes: 11