如何使用 Pathlib 在 Python 中迭代目录

Raf*_*ini 5 python directory glob subdirectory pathlib

我正在使用 Python 3,我需要对文件夹执行一些操作,使用 Pathlib 并检查它们是否是文件夹。

我要做的操作是这样的:

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
Run Code Online (Sandbox Code Playgroud)

我的问题是是否有更好的方法来做到这一点。回顾过去提出的问题,看起来最好的方法是使用 Pahtlib 的 glob 方法。因此,由于我有三个深度级别,所以我尝试了以下方法:

for a in source_path.glob("**/**/**"):
    if a.is_dir():
        print(a)
Run Code Online (Sandbox Code Playgroud)

它几乎可以工作了。问题是,这不仅返回最深层的文件夹,还返回它们的父文件夹。我在格式化 glob 模式时犯了一些错误吗?或者是否存在更好的方法来仅列出最深的_级别元素?

And*_*ell 4

我想你想要:

\n\n
for a in source_path.glob("*/*/*"):\n    if a.is_dir():\n        print(a)\n
Run Code Online (Sandbox Code Playgroud)\n\n

从文档来看:该**模式表示 \xe2\x80\x9c 这个目录和所有子目录,递归地\xe2\x80\x9d,而其中一个*是文本通配符。

\n