3

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?

4

1 回答 1

3

我想你想要:

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

来自文档:该**模式的意思是“递归的这个目录和所有子目录”,而一个*是文本通配符。

于 2018-11-27T10:39:12.933 回答