以Python os.walk为例的递归定义 [英] Recursion definition using Python os.walk as an example

查看:45
本文介绍了以Python os.walk为例的递归定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法掌握如何使用 python 从目录中递归列出文件.是否所有的递归逻辑都发生在模块本身(os.walk)中?

I am having trouble grasping how to recursively list files from a directory using python. Does all the recursion logic take place in the module itself (os.walk)?

def listfiles(path):
    for root, dirs, files in os.walk(path):
        for f in files:
            print(f)

我查找了多种递归列出目录中文件的方法,它们都遵循与上述相同的模式.这似乎是遍历文件.有人可以向我解释这是如何递归完成的吗?

I have looked up multiple ways to recursively list files in a directory and they all follow the same pattern as above. This appears to be iterating through the files. Could someone explain to me how this is being recursively done?

推荐答案

os.walk() 是一个生成器.它在生成结果的同时递归地列出目录.请参阅源代码,但经过简化,它下降了到:

os.walk() is a generator. It recursively lists directories all the while generating the results. See the source code, but simplified, it comes down to:

def walk(top):
    try:
        names = os.listdir(top)
    except error, err:
        return

    dirs, nondirs = [], []
    for name in names:
        if os.path.isdir(os.path.join(top, name)):
            dirs.append(name)
        else:
            nondirs.append(name)

    yield top, dirs, nondirs

    for name in dirs:
        new_path = os.path.join(top, name)
        for x in walk(new_path):  # recursive call
            yield x

此代码在收集目录和常规文件后列出顶部路径,然后向下递归到嵌套目录.递归调用通过显式产生结果来传递.Python 3 版本在那里使用生成器委托:

This code lists the top path after collecting directories and regular files, then recurses down to the nested directories. The recursive calls are passed on by yielding the results explicitly. The Python 3 version uses generator delegation there:

for name in dirs:
    new_path = os.path.join(top, name)
    yield from walk(new_path)

为了简化这一点,我省略了对错误回调、过滤符号链接和自下而上生成的支持.

To simplify this, I omitted the support for error callbacks, filtering symlinks and bottom-up generation.

这篇关于以Python os.walk为例的递归定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆