0

How to add a command for discord py to to backup a JSON file and save as duplicate name.

Example: If i have amounts.json file in same directory of bot.py.

i want it to create a back up with duplicate number while it saves everytime.

Demotry
  • 869
  • 4
  • 21
  • 40
  • You can see an example of how to version file backups here: https://stackoverflow.com/questions/46872708/versioning-file-name-using-python – Patrick Haugh Nov 30 '18 at 03:27
  • One easy thing you can do is to timestamp it. – Kevin He Nov 30 '18 at 04:40
  • [`time.time()`](https://docs.python.org/3/library/time.html#time.time) might be helpful – Kevin He Nov 30 '18 at 04:43
  • you can add that to your filename. for a more readable timestamp you need to `from datetime import datetime`. And every time you save it, you save it to a filename `'amounts-{}'.format(datetime.now().strftime('%Y-%m-%d-%X'))` – Kevin He Nov 30 '18 at 04:55
  • `open('amounts.json', 'w+')` to `'amounts-{}'.format(datetime.now().strftime('%Y-%m-%d-%X'))`, its the filename you want to change right, the `open` statement creates a new file for you to write (hence the `w+`) as the second argument – Kevin He Nov 30 '18 at 05:07

1 Answers1

1

I'm not sure what your needs are. If you want to save the current amounts to amounts.json file and overwrite it every time, your code in the question would suffice.

If you want to save the amounts to a different file so that you can say look back and see the contents of amounts at a some previous time, you can add timestamp to your file by

(assuming you had imported datetime by from datetime import datetime

def _save_with_timestamp():
    with open('amounts-{}.json'.format(datetime.now().strftime('%Y-%m-%d-%X')), 'w+') as f:
        json.dump(amounts, f)

Say, at 2018-11-29-19:00:01 you pressed save and then the contents of amounts might be saved to a json file named amounts-2018-11-29-19:00:02.json.

Kevin He
  • 1,210
  • 8
  • 19