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
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)