42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
import os
|
|
import re
|
|
import gzip
|
|
|
|
|
|
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)
|
|
elif os.path.isdir(uri):
|
|
recurse(uri)
|
|
|
|
|
|
def compress(file):
|
|
with open(file, 'rb') as infile:
|
|
with gzip.open(file + ".gz", 'wb') as zipfile:
|
|
while chunk := infile.read(64 * 1024):
|
|
zipfile.write(chunk)
|
|
print(file + " compressed")
|
|
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]) |