Fix Python – Recursively iterate through all subdirectories using pathlib

Question

Asked By – Oblomov

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.

Now we will see solution for issue: Recursively iterate through all subdirectories using pathlib


Answer

You can use the glob method of a Path object:

p = Path('docs')
for i in p.glob('**/*'):
     print(i.name)

This question is answered By – Jacques Gaudin

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0