栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

递归深度受限制的旅行目录树

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

递归深度受限制的旅行目录树

我认为最简单,最稳定的方法是直接复制

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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/650679.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号