Python discord bot has problems writing to textfiles

Viewed 62

I'm currently working on a little discord bot. To host it for free, I'm using an application on heroku.com which is connected to my github. Everytime I restart the bot it gets some previously stored information from a textfile (works perfectly).

f = open("example_textfile.txt", "r")
example_list = dict(json.loads(f.read()))
f.close()

Everytime a list gets updated it should overwrite the textfile with the updated list like this (does NOT work):

f = open("example_textfile.txt", "w")
f.write(json.dumps(example_list))
f.close()

If I host the bot locally on my PC everything works perfectly (then I need the path, not just the name of the file). But when I host it with Heroku it can only read the files but not overwrite them. Does anyone know why this doesn't work? Or is there any alternative? Would be great if you could help me :D (And sorry for my bad english xD. I'm not native)

1 Answers

This should work


json.dump(example_list, open("example_file.txt", "w"))

The reason the write method may not be working for you is because json.dumps() automatically writes to the file; That is the purpose of the method. You're writing to the program is indicating that whatever json.dumps returns is what will get written to the file...

You should use json.dump | Is writes to the file intaking a dictionary instead!

Related