← Back to Python, page 5

python-0083 · Medium mid

Use pathlib to find the largest files under a directory and report their sizes.

pathlib.Path offers object-oriented paths: / joins parts, rglob walks recursively, stat() gives size, and suffix and stem split names. Combine rglob with is_file and heapq.nlargest to get the top files without sorting everything. Paths work across operating systems.

Full answer
python
import heapq, tempfile
from pathlib import Path

root = Path(tempfile.mkdtemp())
(root / "logs").mkdir()
(root / "logs" / "app.log").write_text("x" * 5000)
(root / "logs" / "old.log").write_text("x" * 12000)
(root / "data.csv").write_text("id,name 1,Asha")
(root / "notes.txt").write_text("x" * 800)

files = (p for p in root.rglob("*") if p.is_file())
top = heapq.nlargest(2, files, key=lambda p: p.stat().st_size)
for p in top:
    print(p.relative_to(root).as_posix(), p.stat().st_size, p.suffix)
print(sorted(p.name for p in root.glob("*.csv")), (root / "logs").is_dir())

Output:

text
logs/old.log 12000 .log
logs/app.log 5000 .log
['data.csv'] True

rglob('*') yields every path below the root, and the generator filters out directories. heapq.nlargest keeps only the top two while scanning, which matters for trees with millions of files. relative_to and as_posix produce readable, platform-neutral output. glob without the r searches one level. For huge trees, os.scandir is faster because it reuses directory entry information, but pathlib is clearer for most scripts.

python
import heapq, tempfile
from pathlib import Path

root = Path(tempfile.mkdtemp())
(root / "logs").mkdir()
(root / "logs" / "app.log").write_text("x" * 5000)
(root / "logs" / "old.log").write_text("x" * 12000)
(root / "data.csv").write_text("id,name 1,Asha")
(root / "notes.txt").write_text("x" * 800)

files = (p for p in root.rglob("*") if p.is_file())
top = heapq.nlargest(2, files, key=lambda p: p.stat().st_size)
for p in top:
    print(p.relative_to(root).as_posix(), p.stat().st_size, p.suffix)
print(sorted(p.name for p in root.glob("*.csv")), (root / "logs").is_dir())

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Path objects join with /
  • rglob walks recursively
  • stat().st_size gives sizes
  • heapq.nlargest avoids a full sort
  • os.scandir for very large trees

Common mistakes

  • Building paths with string concatenation
  • Sorting every file to find the top few

Follow-ups

  • How would you skip hidden directories?
  • How would you handle permission errors during the walk?

Tips

  • Use nlargest