小编Raf*_*ini的帖子

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

我正在使用 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 模式时犯了一些错误吗?或者是否存在更好的方法来仅列出最深的_级别元素?

python directory glob subdirectory pathlib

5
推荐指数
1
解决办法
8035
查看次数

标签 统计

directory ×1

glob ×1

pathlib ×1

python ×1

subdirectory ×1