在Python中列出具有指定深度的目录

Ste*_*anE 24 python

我想要一个函数来返回一个包含指定路径和固定深度的目录的列表,并很快意识到有一些替代方案.我正在使用os.walk但是在计算深度等时代码开始看起来很难看.

什么是最"整洁"的实施?

phi*_*hag 48

如果深度是固定的,那么这glob是一个好主意:

import glob,os.path
filesDepth3 = glob.glob('*/*/*')
dirsDepth3 = filter(lambda f: os.path.isdir(f), filesDepth3)
Run Code Online (Sandbox Code Playgroud)

否则,它应该不会太难使用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)
Run Code Online (Sandbox Code Playgroud)