为什么我的代码中的打破顺序无法停止循环?

2024-09-28 01:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

import os
import sys

sys.setrecursionlimit(1000000)

def searchFilePath(filename, path):
    try:
        for direction in os.listdir(path):
            if direction == filename:
                print(path)
                break
            elif os.path.isfile(os.path.join(path, direction)):
                continue
            else:
                searchFilePath(filename, os.path.join(path, direction))
    except PermissionError:
        pass

searchFilePath("abc.rar", "d:\\")

每次程序找到目标文件时,它都不能立即停止,尽管我使用break结束递归。它总是遍历路径下的所有路径,然后返回结果


Tags: pathinimport路径forosdefsys
3条回答

你用错了breakbreak将您从单个循环中分离出来

for x in some_list:
    for y in another_list:
        for z in yet_another_list:
            break

这将继续循环another_list中的所有值

您想使用return,这将使您脱离整个函数

for x in some_list:
    for y in another_list:
        for z in yet_another_list:
            return z

请注意,这将在通过yet_another_list的第一次迭代中停止,并且仅作为说明代码不起作用的示例

break仅结束电流回路。调用堆栈中任何正在进行的循环都不会退出

您必须从函数返回一个标志,这样父调用也可以知道退出:

def searchFilePath(filename, path):
    try:
        for direction in os.listdir(path):
            if direction == filename:
                print(path)
                return True
            elif os.path.isfile(os.path.join(path, direction)):
                continue
            else:
                found = searchFilePath(filename, os.path.join(path, direction))
                if found:
                    return True
    except PermissionError:
        pass
    return False

break只留下当前循环。必须使用返回值来表示递归的结束

def searchFilePath(filename, path):
    """ returns True if the filename was found in path """
    try:
        for direction in os.listdir(path):
            if direction == filename:
                print(path)
                return True
            elif not os.path.isfile(os.path.join(path, direction)):
                if searchFilePath(filename, os.path.join(path, direction)):
                    return True
    except PermissionError:
        pass
    return False

或者如果您想进一步使用path

def searchFilePath(filename, path):
    """ returns the path, where the filename was found """
    try:
        for direction in os.listdir(path):
            if direction == filename:
                return path
            elif not os.path.isfile(os.path.join(path, direction)):
                found = searchFilePath(filename, os.path.join(path, direction)):
                if found is not None:
                    return found
    except PermissionError:
        pass
    return None

如果使用os.walk,可以将函数简化为:

def searchFilePath(filename, path):
    for path, _, filenames in os.walk(path):
        if filename in filenames:
            return path
    return None

相关问题 更多 >

    热门问题