The answer to this question depends on the way your python program will shut down, if you shut it down 'the normal way' a try-finally
loop would do the trick. Something like this:
with open('counter.txt', 'r') as f:
counter = int(f.readline())
try:
client.run(TOKEN)
finally:
with open('counter.txt', 'w') as f:
f.write(counter)
However if you 'kill' the program that finally
part might not run, a solution to this would be to kill the bot from within discord, with a command containing client.close()
Another way is to modify your counter function so it would always save the current counter whenever it changes
async def token():
global counter
counter = 0
while True:
await asyncio.sleep(5)
counter += 1
with open('counter.txt', 'w') as f:
f.write(counter)
Also note that as your program is right now you set the counter to 0, you'll need to add loading the value too (this:)
with open('counter.txt', 'r') as f:
counter = int(f.readline())
Ofcourse if you dont just want to save a simple counter, you're going to have to use json
or pickle
, but the method stays the same