import os import re import gzip import tempfile from crypt import * def recurse(path, maxsize="50M"): max = parse_size(maxsize) for f in os.listdir(path): uri = os.path.join(path, f) if os.path.isfile(uri): size = os.path.getsize(uri) Hsize = str(human_readable_size(size, 0)) print(f + " : " + Hsize) if size > max: compress(uri, key) elif os.path.isdir(uri): recurse(uri) def compress(file, key): gz = tempfile.SpooledTemporaryFile() with open(file, 'rb') as infile: with gzip.open(gz, 'wb') as zipfile: while chunk := infile.read(64 * 1024): zipfile.write(chunk) print(file + " compressed") encrypt_file(key, gz, file + ".gz.enc") print(file + " encrypted") pass def human_readable_size(size, decimal_places=2): for unit in ['B', 'K', 'M', 'G', 'T']: if size < 1024.0: break size /= 1024.0 return f"{size:.{decimal_places}f}{unit}" def parse_size(size): units = {"B": 1, "K": 2**10, "M": 2**20, "G": 2**30, "T": 2**40} if size[-1].isdigit(): size = size + 'K' number, unit = re.match(r"([0-9]+)([BKMGT])", size, re.I).groups() return int(float(number)*units[unit])