Skip to content

Instantly share code, notes, and snippets.

@alajmo
Created November 25, 2015 18:19
Show Gist options
  • Select an option

  • Save alajmo/df7b8f94211689ee9e97 to your computer and use it in GitHub Desktop.

Select an option

Save alajmo/df7b8f94211689ee9e97 to your computer and use it in GitHub Desktop.
Copy file and append date to filename.
""" Backup files.
"""
import os.path
import shutil
import datetime
ROOT_DIR = os.path.abspath(os.path.join(os.sep, 'backup-from-folder'))
ERROR_LOG_FILE = os.path.join(os.sep, ROOT_DIR, 'logs', 'errorlog.txt')
CURRENT_DATE = str(datetime.datetime.now().date())
FILES_TO_BACKUP = [
'file-1.txt',
'file-2.txt'
]
def backup_data_entry_files():
""" Backup files.
"""
for filename in FILES_TO_BACKUP:
if os.path.isfile(filename):
# 1. Extract Directory name.
dirname = os.path.dirname(filename)
# 2. Extract filename and extension.
fn, fe = os.path.splitext(filename)
# 3. Append date to new filename.
new_filename = os.path.basename(fn + '-' + CURRENT_DATE + fe)
# 4. Construct the new destination.
destination = os.path.join(dirname, 'backup-folder-name', new_filename)
# 5. Attempt to copy.
if not os.path.exists(destination):
try:
shutil.copy(os.path.normpath(filename), destination)
except IOError, e:
with open(ERROR_LOG_FILE, 'a') as f:
f.write('%s \nUnable to copy file. %s' % (CURRENT_DATE, e))
else:
with open(ERROR_LOG_FILE, 'a') as f:
f.write('%s\nFile "%s" does not exist\n\n' % (CURRENT_DATE, filename))
if __name__ == '__main__':
backup_data_entry_files()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment