我认为最简单,最稳定的方法是直接复制
os.walk
源代码的功能并插入自己的深度控制参数。
import osimport os.path as pathdef walk(top, topdown=True, onerror=None, followlinks=False, maxdepth=None): islink, join, isdir = path.islink, path.join, path.isdir try: names = os.listdir(top) except OSError, err: if onerror is not None: onerror(err) return dirs, nondirs = [], [] for name in names: if isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs if maxdepth is None or maxdepth > 1: for name in dirs: new_path = join(top, name) if followlinks or not islink(new_path): for x in walk(new_path, topdown, onerror, followlinks, None if maxdepth is None else maxdepth-1): yield x if not topdown: yield top, dirs, nondirsfor root, dirnames, filenames in walk(args.directory, maxdepth=2): #...
如果您对所有这些可选参数都不感兴趣,则可以大幅缩减该函数:
import osdef walk(top, maxdepth): dirs, nondirs = [], [] for name in os.listdir(top): (dirs if os.path.isdir(os.path.join(top, name)) else nondirs).append(name) yield top, dirs, nondirs if maxdepth > 1: for name in dirs: for x in walk(os.path.join(top, name), maxdepth-1): yield xfor x in walk(".", 2): print(x)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)