Skip to content

Instantly share code, notes, and snippets.

@GMadorell
Last active August 29, 2015 14:08
Show Gist options
  • Save GMadorell/5d8abe1884c5e32946d6 to your computer and use it in GitHub Desktop.
Save GMadorell/5d8abe1884c5e32946d6 to your computer and use it in GitHub Desktop.
backup a file in python
def backup_file(file_path, backup_path=None, verbose=True):
"""
If the given 'file_path' exists, this function creates a copy of it.
Backup is done at 'backup_path'.backup# (backup_path defaults to
'file_path'.
If 'verbose' is set (defaults to True), prints output when backing up.
"""
if not os.path.isfile(file_path):
return
if not backup_path:
backup_path = file_path
ensure_directory(backup_path)
count = 1
file_name_template = "{}.backup{}"
backup_name = file_name_template.format(backup_path, count)
while os.path.isfile(backup_name):
count += 1
backup_name = file_name_template.format(backup_path, count)
with open(file_path) as original_file, \
open(backup_name, "w") as backup_file:
backup_file.write(original_file.read())
if verbose:
print(("'{}' already found! Backing the file up to '{}' before doing "
"any changes.").format(file_path, backup_name))
def ensure_directory(file_path):
d = os.path.dirname(file_path)
if d and not os.path.exists(d):
os.makedirs(d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment