Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively iterate through all subdirectories using pathlib

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.

like image 799
user1934212 Avatar asked Jun 06 '18 07:06

user1934212


3 Answers

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

path = Path("docs")
for p in path.rglob("*"):
     print(p.name)
like image 138
pylang Avatar answered Nov 12 '22 08:11

pylang


You can use the glob method of a Path object:

p = Path('docs')
for i in p.glob('**/*'):
     print(i.name)
like image 117
Jacques Gaudin Avatar answered Nov 12 '22 08:11

Jacques Gaudin


To find just folders the right glob string is:

'**/'

So to find all the paths for all the folders in your path do this:

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

If you just want the folder names without the paths then print the name of the folder like so:

p = Path('docs')
for child in p.glob('**/'):
    print(child.name)
like image 11
TKK Avatar answered Nov 12 '22 09:11

TKK