Use <code>Path.glob()</code> and <code>Path.rglob()</code> for typed versions of <code>glob.glob()</code>

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.

[If the formatting of this post looks odd in your feed reader, visit the original article]

添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论