Instantly share code, notes, and snippets.

What would you like to do?
File Backup Python Script

File Backup Python Script

A simple Python script for backing up a file to a directory with a timestamp every time it changes.

Works with both Python 2 and Python 3.


After installing Python, you can run it command line like this:

python file_to_backup directory_to_backup_to
#!/usr/bin/env python
import os
import sys
import time
import datetime
import shutil
def timestamp():
return datetime.datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S-%f')
def mkdirp(path):
if not os.path.exists(path):
def main(argv):
if len(argv) < 3:
print('USAGE: %s save_file backup_dir' % (argv[0]))
return 1
save_file = argv[1]
backup_dir = argv[2]
save_file_basename = os.path.basename(save_file)
last_modified = None
while True:
modified = None
modified = str(os.path.getmtime(save_file))
except Exception as ex:
print('Reading file modified failed: %s' % (str(ex)))
if last_modified != modified:
backup_file_name = '%s_%s' % (timestamp(), save_file_basename)
backup_file_path = os.path.join(backup_dir, backup_file_name)
shutil.copyfile(save_file, backup_file_path)
last_modified = modified
print('Backup created: %s' % (backup_file_name))
except Exception as ex:
print('Backup failed: %s' % (str(ex)))
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment