获取文件夹中所有嵌套目录 python

0 投票
1 回答
2905 浏览
提问于 2025-04-18 02:51

这是目录结构

10
  files
    2009
    2010
11
  files
    2007
    2010
    2006

我想获取文件夹里面所有目录的完整路径名

import os
x = os.walk('.').next()[1]

print x # prints ['33', '18', '27', '39', '2', '62', '25']

for a in x:
    y = os.walk(a).next()[1]

print y # prints ['files']

我试过用嵌套的循环,但出现了停止迭代的错误。

我想得到的结果大概是这样的,

['10/files/2009','10/files/2010','11/files/2007','11/files/2010','10/files/2006']

在Python中怎么做呢?

1 个回答

1

看起来你想要获取最深层的文件夹。如果你使用 topdown=False 这个参数,程序会按照深度优先的方式遍历,这样会先列出最深层的文件夹,然后再列出它们的父文件夹。

为了过滤掉更高层的文件夹,你可以用一个集合来记录父文件夹,这样就可以不报告那些文件夹了:

import os

def listdirs(path):
    seen = set()
    for root, dirs, files in os.walk(path, topdown=False):
        if dirs:
            parent = root
            while parent:
                seen.add(parent)
                parent = os.path.dirname(parent)
        for d in dirs:
            d = os.path.join(root, d)
            if d not in seen:
                yield d

for d in listdirs('.'):
    print(d)

撰写回答