Skip to main content

Use Path.glob() and Path.rglob() for typed versions of glob.glob()

  • Posted

These functions let you search a directory or recurse into it, and they return Path objects.

Recently I’ve been getting a lot of use out of the glob module, for finding files that match a particular pattern:

from glob import glob

top_level_html_files = glob("*.html")
all_html_files = glob("**/*.html", recursive=True)

But these functions return strings, and I’ve been trying to use Path objects as much as possible.

It turns out the pathlib module has glob() and rglob() functions that do sometrhing very similar, but they return Path objects:

from pathlib import Path

top_level_html_files = Path.cwd().glob("*.html")
all_html_files = Path.cwd().rglob("*.html")

This isn’t new – indeed, it’s mentioned in Trey Hunner’s 2018 blog post that persuaded me to start using pathlib – but somehow I’d forgotten about it.