daily log 02-25-21

less than 1 minute read

How to get the sizes of each directory?


import os
from pathlib import Path

current_folder = "/Volumes/EHD_3/"
csv_contents = ""

## ====================================
# HELPER FUNCTIONS!
## ====================================

def get_size(path):
    return sum(p.stat().st_size for p in Path(path).rglob('*'))

def humanized_size(num, suffix='B', si=False):
    if si:
        units = ['','K','M','G','T','P','E','Z']
        last_unit = 'Y'
        div = 1000.0
    else:
        units = ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']
        last_unit = 'Yi'
        div = 1024.0
    for unit in units:
        if abs(num) < div:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= div
    return "%.1f%s%s" % (num, last_unit, suffix)

## ====================================
## ====================================


for i in os.listdir(current_folder):
    path = current_folder + i
    if os.path.isdir(path):
        size = get_size(path)
        human_size = humanized_size(size)
        csv_contents += "{},{},{}\n".format(i, human_size, size)

output_file = current_folder + 'sizes.csv'
fp = open(output_file, "w")
fp.write(csv_contents)
fp.close()