在Python中按指定深度列出目录

38 投票
6 回答
39283 浏览
提问于 2025-04-17 00:11

我想要一个函数,能够返回一个指定路径下的文件夹列表,并且可以设置一个固定的深度。后来我发现有几种不同的方法可以做到这一点。我经常使用os.walk这个工具,但当我开始计算深度的时候,代码看起来就变得很乱了。

那么,什么样的实现方式才是最“简洁”的呢?

6 个回答

4

这是一个简单的递归解决方案,使用了 os.scandir 这个功能:

def _walk(path, depth):
    """Recursively list files and directories up to a certain depth"""
    depth -= 1
    with os.scandir(path) as p:
        for entry in p:
            yield entry.path
            if entry.is_dir() and depth > 0:
                yield from _walk(entry.path, depth)
4

这不是特别“整洁”,但是在类似UNIX的操作系统中,你可以使用一个系统工具,比如“find”,然后把它当作一个外部程序来执行,比如:

from subprocess import call
call(["find", "-maxdepth", "2", "-type", "d"])

接着,你可以把输出结果存到一个字符串变量里,方便后续处理。

65

如果深度是固定的,使用glob是个不错的选择:

import glob,os.path
filesDepth3 = glob.glob('*/*/*')
dirsDepth3 = filter(lambda f: os.path.isdir(f), filesDepth3)

否则,使用os.walk应该也不难:

import os,string
path = '.'
path = os.path.normpath(path)
res = []
for root,dirs,files in os.walk(path, topdown=True):
    depth = root[len(path) + len(os.path.sep):].count(os.path.sep)
    if depth == 2:
        # We're currently two directories in, so all subdirs have depth 3
        res += [os.path.join(root, d) for d in dirs]
        dirs[:] = [] # Don't recurse any deeper
print(res)

撰写回答