Recursively iterate through all subdirectories using pathlib

user1934212 picture user1934212 · Jun 6, 2018 · Viewed 32.6k times · Source

How can I use pathlib to recursively iterate over all subdirectories of a given directory?

p = Path('docs')
for child in p.iterdir(): child

only seems to iterate over the immediate children of a given directory.

I know this is possible with os.walk() or glob, but I want to use pathlib because I like working with the path objects.

Answer

pylang picture pylang · Jan 4, 2019

Use Path.rglob (substitutes the leading ** in Path().glob("**/*")):

path = Path("docs")
for p in path.rglob("*"):
     print(p.name)