4

I'm working with Python 3 and I need to perform some operations on folders, using Pathlib and checking if they are folders.

The operation I'm gonna do is something like this:

from pathlib import Path
source_path = Path("path_directory_string")

for a in source_path.iterdir():
    if a.is_dir():
        for b in a.iterdir():
            if b.is_dir():
                for c in b.iterdir():
                    if c.is_dir():
                        # do something

My question is if there is a better way to do this. Looking through the past asked questions, it looks like the best way to do this is using the method glob of Pahtlib. So, since I have three levels of depth, I tried this:

for a in source_path.glob("**/**/**"):
    if a.is_dir():
        print(a)

and it almost works. The issue is that this returns not just the deepest-level folders, but also their parents. Did I make some mistakes formatting the glob pattern? Or does it exist a better way to list just the deepest_level elements?

1 Answer 1

4

I think you want:

for a in source_path.glob("*/*/*"):
    if a.is_dir():
        print(a)

From the documentation: The ** pattern means “this directory and all subdirectories, recursively”, whereas one * is a text wildcard.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.