|
| 1 | +import os |
| 2 | +import matplotlib.pyplot as plt |
| 3 | + |
| 4 | + |
| 5 | +def get_size_format(b, factor=1024, suffix="B"): |
| 6 | + """ |
| 7 | + Scale bytes to its proper byte format |
| 8 | + e.g: |
| 9 | + 1253656 => '1.20MB' |
| 10 | + 1253656678 => '1.17GB' |
| 11 | + """ |
| 12 | + for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: |
| 13 | + if b < factor: |
| 14 | + return f"{b:.2f}{unit}{suffix}" |
| 15 | + b /= factor |
| 16 | + return f"{b:.2f}Y{suffix}" |
| 17 | + |
| 18 | + |
| 19 | +def get_directory_size(directory): |
| 20 | + """Returns the `directory` size in bytes.""" |
| 21 | + total = 0 |
| 22 | + try: |
| 23 | + # print("[+] Getting the size of", directory) |
| 24 | + for entry in os.scandir(directory): |
| 25 | + if entry.is_file(): |
| 26 | + # if it's a file, use stat() function |
| 27 | + total += entry.stat().st_size |
| 28 | + elif entry.is_dir(): |
| 29 | + # if it's a directory, recursively call this function |
| 30 | + total += get_directory_size(entry.path) |
| 31 | + except NotADirectoryError: |
| 32 | + # if `directory` isn't a directory, get the file size then |
| 33 | + return os.path.getsize(directory) |
| 34 | + except PermissionError: |
| 35 | + # if for whatever reason we can't open the folder, return 0 |
| 36 | + return 0 |
| 37 | + return total |
| 38 | + |
| 39 | + |
| 40 | +def plot_pie(sizes, names): |
| 41 | + """Plots a pie where `sizes` is the wedge sizes and `names` """ |
| 42 | + plt.pie(sizes, labels=names, autopct=lambda pct: f"{pct:.2f}%") |
| 43 | + plt.title("Different Sub-directory sizes in bytes") |
| 44 | + plt.show() |
| 45 | + |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + import sys |
| 49 | + folder_path = sys.argv[1] |
| 50 | + |
| 51 | + directory_sizes = [] |
| 52 | + names = [] |
| 53 | + # iterate over all the directories inside this path |
| 54 | + for directory in os.listdir(folder_path): |
| 55 | + directory = os.path.join(folder_path, directory) |
| 56 | + # get the size of this directory (folder) |
| 57 | + directory_size = get_directory_size(directory) |
| 58 | + if directory_size == 0: |
| 59 | + continue |
| 60 | + directory_sizes.append(directory_size) |
| 61 | + names.append(os.path.basename(directory) + ": " + get_size_format(directory_size)) |
| 62 | + |
| 63 | + print("[+] Total directory size:", get_size_format(sum(directory_sizes))) |
| 64 | + plot_pie(directory_sizes, names) |
| 65 | + |
| 66 | + |
| 67 | + |
0 commit comments