159

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.

Oblomov
  • 8,953
  • 22
  • 60
  • 106

6 Answers6

245

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

path = Path("docs")
for p in path.rglob("*"):
     print(p.name)
pylang
  • 40,867
  • 14
  • 129
  • 121
136

You can use the glob method of a Path object:

p = Path('docs')
for i in p.glob('**/*'):
     print(i.name)
Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
14

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)
TKK
  • 199
  • 1
  • 6
8

Use list comprehensions:

(1) [f.name for f in p.glob("**/*")]  # or
(2) [f.name for f in p.rglob("*")]

You can add if f.is_file() or if f.is_dir() to (1) or (2) if you want to target files only or directories only, respectively. Or replace "*" with some pattern like "*.txt" if you want to target .txt files only.

See this quick guide.

dzenilee
  • 308
  • 4
  • 6
  • 4
    What is the point in using list comprehension? How does that complement the existing answers? – Jacques Gaudin Feb 05 '20 at 13:06
  • 2
    I was looking at the other answers that were printing the results, so I was offering it as an alternative. But you're right, the original post doesn't make it explicit it's needed. – dzenilee May 05 '20 at 14:44
  • We might as well add generator expressions as well. – MrR Apr 26 '22 at 18:50
8

In Python 3.12 (not released as of writing of this post) you will be able to use pathlib.Path.walk()

winderland
  • 362
  • 3
  • 7
7

pathlib has glob method where we can provide pattern as an argument.

For example : Path('abc').glob('**/*.txt') - It will look for current folder abc and all other subdirectories recursively to locate all txt files.

Sijan Bhandari
  • 2,941
  • 3
  • 23
  • 36