← all snippets

find-large-files

Lists every file under a directory that's at or above a given size threshold. Use it to hunt down what's eating disk space or bloating a repo/build output.

Python 3 #03

Source

find-large-files.py
#!/usr/bin/env python3
"""List files in a directory over a given size threshold (bytes)."""
import sys
from pathlib import Path

if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit("usage: find-large-files.py <dir> <min_bytes>")
    root = Path(sys.argv[1]).resolve()
    try:
        threshold = int(sys.argv[2])
    except ValueError:
        sys.exit("min_bytes must be an integer")
    if not root.is_dir():
        sys.exit(f"not a directory: {root}")
    for p in sorted(root.rglob("*")):
        if p.is_file() and p.stat().st_size >= threshold:
            print(f"{p.stat().st_size:>12}  {p}")

Input

dirstring — positional argument, directory to scan recursively, e.g. .
min_bytesinteger — positional argument, minimum file size to report, e.g. 10485760 (10 MB)

Output

Prints one line per matching file: right-aligned byte size, two spaces, then the absolute path. Files are visited in sorted path order. Exits non-zero with a message if dir isn't a directory or min_bytes isn't an integer.

Usage

$ python3 find-large-files.py . 10485760
    52428800  /repo/build/app.tar.gz
    15728640  /repo/data/dump.sql

Config

No configuration required.

Security notes

  • Uses pathlib for all path handling — no shell globbing, no os.system.
  • The scan root is resolved to an absolute path before walking, so relative-path confusion can't send it outside where you expect.
  • Numeric input is validated with a caught int() conversion instead of letting a bad value crash with a raw traceback.