From 35faa3f4a32b7e25953a5585c65c2c809d285b13 Mon Sep 17 00:00:00 2001 From: Tilman Date: Mon, 27 Nov 2023 17:19:03 +0100 Subject: [PATCH] selective-backup.py --- python/selective-backup.py | 59 ++++++++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 18 deletions(-) diff --git a/python/selective-backup.py b/python/selective-backup.py index bd2248e..05c5c3c 100644 --- a/python/selective-backup.py +++ b/python/selective-backup.py @@ -1,29 +1,52 @@ -import shutil from datetime import datetime +from zipfile import ZipFile import os +import shutil + +filelist = "/media/hd/cloud/Tilman/Computer/selective-backups/filelist.txt" + +days_to_keep = 5 +months_to_keep = 5 daily_dir = "/media/hd/cloud/Tilman/Computer/selective-backups/daily/" -weekly_dir = "" -monthly_dir = "" +monthly_dir = "/media/hd/cloud/Tilman/Computer/selective-backups/monthly/" -basedir = "/media/hd/cloud/" -filelist = "/media/hd/cloud/Tilman/Computer/selective-backups/filelist.txt" +basedir = "/media/hd/cloud" now = datetime.now() -date_time = now.strftime("%Y-%m-%d_") +today = datetime.today() +target_filename = today.strftime('%Y-%m-%d') + "_selective-backup.zip" with open(filelist) as file: lines = [line.rstrip() for line in file] -for line in lines: - #f_basename = os.path.basename(line) - target_filename = date_time + line.replace("/","|") + ".tar.gz" - print(target_filename) - src_path = basedir + line - src_file = os.path.basename(src_path) - src_dir = os.path.dirname(src_path) - print(src_dir) - shutil.make_archive(daily_dir + target_filename, 'gztar', src_dir, src_file) - +#os.chdir(basedir) + +# backup directories and files +with ZipFile(daily_dir + target_filename, 'w') as zip: + for line in lines: + if os.path.isdir(basedir + line): + for root, dirs, files in os.walk(basedir + line): + for file in files: + file_path = os.path.join(root, file) + zip.write(file_path) + else: + zip.write(basedir + line) + +# if first of month, copy over +if now.day == 1: + shutil.copy(daily_dir + target_filename, monthly_dir) + +# delete old backups +for filename in os.listdir(daily_dir): + date_object = datetime.strptime(filename[:10], '%Y-%m-%d') + delta = today - date_object + if delta.days > days_to_keep: + os.remove(daily_dir + filename) + +for filename in os.listdir(monthly_dir): + date_object = datetime.strptime(filename[:10], '%Y-%m-%d') + num_months = (today.year - date_object.year) * 12 + (today.month - date_object.month) + if num_months > months_to_keep: + os.remove(monthly_dir + filename) + -#os.path.basename -#shutil.make_archive(output_filename, 'zip', dir_name) \ No newline at end of file