List directories with a specified depth in Python

后端 未结 4 1562
故里飘歌
故里飘歌 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 14:56

    A simple, recursive solution using 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)
    

提交回复
热议问题