Python获取目录和子目录的递归列表

2024-04-27 02:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到一个包含每个目录及其子目录的元组列表,例如,有这样一个树:

-A
---AA
---AB
-----ABA
-----ABB
-B
---BA
---BB

我会得到这样一个列表:

[
    (A, [
            (AA, []),
            (AB, [
                     (ABA, []),
                     (ABB, []),
                 ]),
        ]),
    (B, [
            (BA, []),
            (BB, []),
        ]),
]

我对这些文件不感兴趣。你知道吗

我试过使用os.步行('.'.'),但在转到下一个条目之前,我没有进入目录。你知道吗

你知道吗?你知道吗


Tags: 文件目录列表abos条目aa元组
1条回答
网友
1楼 · 发布于 2024-04-27 02:18:32

我们可以获得立即子目录的列表,包括:

from os import listdir
from os.path import join, isdir

subdirs = [join(d, o) for o in listdir(d) if isdir(join(d,o))]

我们可以通过递归的方式将其用于:

from os import listdir
from os.path import join, isdir

def obtain_subdir_tuples(d):
    subdirs = [join(d, o) for o in listdir(d) if isdir(join(d,o))]
    return (d, [obtain_subdir_tuples(subdir) for subdir in subdirs])

然而,这样做的一个潜在问题是,我们也可以遵循符号链接并陷入无限递归:目录中指向该目录的父目录(或通常的父目录)的符号链接。在这种情况下,目录本身就是一个子目录。我们可以通过首先查看它是否是与islink的符号链接来避免这种情况:

from os import listdir
from os.path import join, isdir, islink

def obtain_subdir_tuples(d):
    subdirs = [join(d, o)
               for o in listdir(d)
               if isdir(join(d, o)) and not islink(join(d, o))]
    return (d, [obtain_subdir_tuples(subdir) for subdir in subdirs])

相关问题 更多 >