Reputation: 95
I'm trying to edit a dictionary I put in a json database and have simplified the code down to just the simple code but it isn't working: (python)
with open ("./userdata/" + str(int(author.id)) + ".json", "r") as f:
fileLoaded = json.load(f)
fileLoaded["dollars"] -= cost
But the file isn't being modified. I know for a fact I'm accessing the correct file because it's not throwing up any errors and I can read fileLoaded. What am I doing wrong?
Thanks friends
Upvotes: 1
Views: 822
Reputation: 1910
You're not writing it to the file. json.load
doesn't give a "magical reference" which can be used to edit the file. After modifying the dictionary, save it with json.dump
. Like this:
f.close()
with open("./userdata/" + str(int(author.id)) + ".json", 'w' as f):
json.dump(fileLoaded, f)
Upvotes: 0
Reputation: 90
You need to open the file, and then dump the file after you have edited it in order for it to save. Try adding this to the bottom of the code:
with open ("./userdata/" + str(int(author.id)) + ".json", "w") as f:
json.dump(fileLoaded, f)
Upvotes: 3