brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python pathlib rglob finds files recursively without os.walk

Python
~/tips/tip-python-pathlib-rglob-finds-files

from pathlib import Path

Walks a directory tree and yields matching files as Path objects, with sizes and text readers attached.

For simple file searches I reach for pathlib before I write an os.walk loop.

from pathlib import Path

for p in sorted(Path("/var/log").rglob("*.log")):
    print(p, p.stat().st_size)

rglob("*.log") walks the directory tree below the path and yields every match as a Path object, like calling glob("**/*.log"). Each result carries .stat(), .read_text() and .suffix, so no string joining is needed. It returns a generator, so wrap it in sorted() for a stable order. Hidden files are included. Some files under /var/log are only readable by root, so read_text() on them can fail with a permission error when you run it as a normal user.

Further reading: pathlib documentation

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link