Python try-except-except

Python try-except-except

我将包括这段代码应该完成的任务的描述,以防有人需要它来回答我。

#Write a function called "load_file" that accepts one 
#parameter: a filename. The function should open the
#file and return the contents.#
#
# - If the contents of the file can be interpreted as
#   an integer, return the contents as an integer.
# - Otherwise, if the contents of the file can be
#   interpreted as a float, return the contents as a
#   float.
# - Otherwise, return the contents of the file as a
#   string.
#
#You may assume that the file has only one line.
#
#Hints:
#
# - Don't forget to close the file when you're done!
# - Remember, anything you read from a file is
#   initially interpreted as a string.


#Write your function here!
def load_file(filename):
    file=open(filename, "r")
    try:
        return int(file.readline())
    except ValueError:
        return float(file.readline())
    except:
        return str(file.readline())
    finally:
        file.close()


#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print 123, followed by <class 'int'>.
contents = load_file("LoadFromFileInput.txt")
print(contents)
print(type(contents))

当使用包含“123”的文件测试代码时,一切正常。当网站加载另一个文件以测试此代码时,出现以下错误:

[Executed at: Sat Feb 2 7:02:54 PST 2019]

    We found a few things wrong with your code. The first one is shown below, and the rest can be found in full_results.txt in the dropdown in the top left:

    We tested your code with filename = "AutomatedTest-uwixoW.txt". We expected load_file to return the float -97.88285. However, it instead encountered the following error:

    ValueError: could not convert string to float:

所以我猜错误发生在第一个 except 语句中,但我不明白为什么。如果在将文件中的值转换为 float 时发生错误,代码不应该转到第二个 except 语句吗?在第二个 except 中,它会被转换为字符串,这仍然可以工作吗?我猜我对 try-except(specified error)-except(no specified error) 的工作原理有一些误解。

很抱歉post。

不,只有 except 块中的一个 - 第一个匹配异常的块 - 将被执行。您所描述的行为对应于

except ValueError:
    try:
        return float(file.readline())
    except:
        return str(file.readline())

shouldnt the code just go to the second except statement ?

不:此 "flat" try/except 语句仅适用于 first try 块。如果那里发生异常,except 分支会捕获此异常并立即评估适当的块。如果这个块中发生异常,它不会被任何东西捕获,因为那里没有 try 块。

因此,您必须执行大量嵌套 try/except 语句:

try:
    do_this()
except ValueError:
    try:
        do_that()
    except ValueError:
        do_this()
    except:
        do_that_one()
except:
    # a whole bunch of try/except here as well

您可能需要添加额外的嵌套级别。

就您需要编写的代码量而言,这是非常低效的。更好的选择可能是:

data = file.readline()
for converter in (int, float, str):
    try:
        return converter(data)
    except:
        pass

请注意,如果你这样做 converter(file.readline()),每次迭代都会读取一个新行(或者,在你的情况下,在任何新的 try/except 块中),这可能不是你需要的.

def load_file(filename):
    file=open(filename, "r")
    try:
        val = file.readline()
        return int(val)
    except ValueError:
        try:
            return float(val)
        except:
            return str(val)
    finally:
        file.close()