如何停止python递归 [英] How to stop python recursion

查看:38
本文介绍了如何停止python递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个递归搜索文件的函数,我希望它在找到第一个文件时停止递归:

I made a function that searches files recursively and I want it to stop recursion when the first file is found:

def search_file(path):
    for name in os.listdir(path):
        sub = os.path.join(path, name)
        if os.path.isfile(sub):
            return sub#And break recursion
        else:
            search_file(sub)

推荐答案

返回一个标志,表明文件是否被找到.当你调用search_file时,如果返回值为True则返回.

Return a flag that says whether the file was found. When you call search_file, return if the return value is True.

这篇关于如何停止python递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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