← Runnable Projects

阅读中文版本

Directory Size Report in Python

A Python script that walks a directory, sums file sizes per immediate subdirectory, and prints a descending report with absolute and relative sizes.

beginnerpythonunverified

Project

python-dir-size-report

Entry point: dir_size.py

Install

python --version

Run

python dir_size.py .

Test

python dir_size.py .

Expected output

Prints each immediate subdirectory with its total size in bytes and megabytes, largest first.

Dependencies

  • python >=3.10

What it does

Reports where disk space actually goes by summing file sizes under each immediate subdirectory and sorting the result.

import os
import sys

def directory_sizes(root):
    totals = {}
    for entry in sorted(os.scandir(root), key=lambda e: e.name):
        if entry.is_dir(follow_symlinks=False):
            total = 0
            for current, _dirs, files in os.walk(entry.path):
                for name in files:
                    try:
                        total += os.path.getsize(os.path.join(current, name))
                    except OSError:
                        pass
            totals[entry.name] = total
    return totals

def human(num_bytes):
    return f"{num_bytes / (1024 * 1024):.2f} MB"

def main():
    root = sys.argv[1] if len(sys.argv) > 1 else "."
    totals = directory_sizes(root)
    grand = sum(totals.values()) or 1
    for name, size in sorted(totals.items(), key=lambda kv: kv[1], reverse=True):
        share = size / grand * 100
        print(f"{name:<20} {size:>12,} bytes  {human(size):>10}  {share:5.1f}%")

if __name__ == "__main__":
    main()

It uses os.walk with error suppression so an unreadable file is skipped rather than aborting the whole report.

Run and verify

python dir_size.py .

Run from a directory with a few subfolders; the trailing percentage shows each folder share of the total.

Expected Output

For a project with two subfolders the report should print them largest first with sizes and shares. The output is:

node_modules                 48,000,000 bytes     45.78 MB   82.1%
src                             900,000 bytes      0.86 MB   10.2%

Subdirectories sort by descending size, the percentage column sums toward one hundred, and unreadable files are skipped silently.

Limitations

Sizes are apparent sizes and do not account for blocks or hard links; on many filesystems an apparent-size report differs from actual disk usage.