Travel directory tree with limited recursion depth

前端 未结 2 683
天命终不由人
天命终不由人 2020-11-29 08:59

I need to process all files in a directory tree recursively, but with a limited depth.

That means for example to look for files in the current directory and the fir

2条回答
  •  暖寄归人
    2020-11-29 09:38

    Starting in python 3.5, os.scandir is used in os.walk instead of os.listdir. It works many times faster. I corrected @kevin sample a little.

    import os
    
    def walk(top, maxdepth):
        dirs, nondirs = [], []
        for entry in os.scandir(top):
            (dirs if entry.is_dir() else nondirs).append(entry.path)
        yield top, dirs, nondirs
        if maxdepth > 1:
            for path in dirs:
                for x in walkMaxDepth(path, maxdepth-1):
                    yield x
    
    for x in walk(".", 2):
        print(x)
    

提交回复
热议问题