I am storing the points of every user on a Discord server in a .json
file. When a user deserves an extra point, the following code in run and their point increments in the .json
file.
user_id = msg.author.id
user_name = msg.author.display_name
with open("firework_economy.json", 'r ') as f:
data = json.load(f)
if str(user_id) in data:
print("Account already made")
data[str(user_id)]["Fireworks"] = 1
json.dump(data, f)
else:
#data[str(user_id)] = {}
data[str(user_id)]["Fireworks"] = 1
json.dump(data, f)
await msg.channel.send(f"{msg.author.mention} earned 1 firework!")
I am expecting that the .json files changes from:
{
"766571696491986965": {
"Fireworks": 5}
}
to:
{
"766571696491986965": {
"Fireworks": 6}
}
But I am getting:
{
"766571696491986965": {
"Fireworks": 5}
}{"766571696491986965": {"Fireworks": 6}}
CodePudding user response:
When you read fully the contents of a file, the file pointer gets to the end of the file. Hence when you are writing to it, you are writing at the end of the file.
Using f.seek(0, 0)
before your json.dump(...)
fixes your problem.