List directories with a specified depth in Python

后端 未结 4 1571
故里飘歌
故里飘歌 2020-12-28 14:26

I\'m want a function to return a list with directories with a specified path and a fixed depth and soon realized there a few alternatives. I\'m using os.walk quite a lot but

4条回答
  •  不知归路
    2020-12-28 15:10

    If the depth is fixed, glob is a good idea:

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

    Otherwise, it shouldn't be too hard to use 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)
    

提交回复
热议问题