gpt4 book ai didi

python - 错误处理但仍然收到 ValueError

转载 作者:太空宇宙 更新时间:2023-11-04 09:56:34 26 4
gpt4 key购买 nike

我正在努力解决这个关于错误处理的挑战。也许我离题太远了!

挑战说明:

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.

我收到 ValueError: could not convert string to float: "b>a!\{\'"

错误处理是我的错吗?

def load_file(file):

file = open(file, "r")
all_lines = file.read()

try:
return int(all_lines)

except ValueError:
return float(all_lines)

else:
return all_lines


file.close()

最佳答案

你需要做类似的事情

with open(file, "r") as file_handle:
all_lines = file.read()
try:
return int(all_lines)
except ValueError:
pass
try:
return float(all_lines)
except ValueError:
pass

return all_lines

重点是您根本不关心这些错误,因为它们只是意味着您需要继续进行下一个选项。

我还要指出 with 构造负责为您关闭文件。如果你想执行 file = open(file, "r") 那么你需要将你的返回值存储到一个变量中,然后执行 file.close()在你返回之前。

关于python - 错误处理但仍然收到 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45573217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com