【发布时间】:2019-06-26 21:44:20
【问题描述】:
我将包含此代码应该执行的任务的描述,以防有人需要它来回答我。
#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 语句中,但我不明白为什么。如果将文件中的值转换为浮点数时发生错误,代码不应该转到第二个except 语句吗?而在第二个except 中,它将被转换为字符串,这仍然可以工作吗?我猜我误解了try-except(specified error)-except(no specified error) 的工作原理。
抱歉,帖子太长了。
【问题讨论】:
-
另外,如果错误发生在
try:块中,则该行已被读取,并且下次调用readline()时,它将读取文件中的下一行,因此您的 @987654330 @ 代码不会在与失败的值相同的值上运行,而是在文件中的下一个值上运行。也许将读取的行放在 var 中,并在try和except块中返回 var 的转换。 -
这是下一个发生的问题,用你的建议解决了。谢谢。
标签: python try-except