I am creating a Discord bot using Discord.py. I have created a command that will update an external JSON file with a user-specified value. While testing the command I noticed that certain words, such as tes
, will add an unnecessary curly brace at the end of the JSON file. This problem only occurs with certain words, most work without any issues.
Python file
import json with open("./file.json", "r+") as file: f = json.load(file) file.truncate() f["key"] = "tes" file.seek(0) json.dump(f, file, indent = 4)
JSON file
{ "key": "tes" } }
I have tried using f.update({"key": "tes"})
but there is no difference.
EDIT:
The problem was resolved by moving file.truncate()
below file.seek(0)
Advertisement
Answer
So – I know you got this working, but your file.truncate()
and file.truncate()
are a little black-magic-ey, and not used very much which will make your code less idiomatic, and more difficult to maintain.
I think this would be cleaner if you used separate filehandles for the reading and writing to the file.
filename = './file.json' with open(filename) as fp: jsonstuff = json.load(fp) jsonstuff['key'] = 'tes' with open(filename, "w") as fp: json.dump(jsonstuff, fp, indent=4)