[英]Try except not catching FileNotFoundError
我正在尝试捕获 FileNotFoundError 并在它发生时破坏代码,但由于某种原因它不起作用,我仍然收到错误并且代码没有破坏,这是我的代码
file_name = input("Choose a file: ")
def split_columns(file_name):
x_values = []
y_values = []
try:
with open(file_name) as f:
for line in f:
row_values = line.split()
print(row_values)
x_values.append(float(row_values[0]))
y_values.append(float(row_values[1]))
except FileNotFoundError:
print('This file does not exist, try again!')
raise
return x_values, y_values
我做错什么了?
从function中取出try/except
,放到调用function的循环中。
def split_columns(file_name):
x_values = []
y_values = []
with open(file_name) as f:
for line in f:
row_values = line.split()
print(row_values)
x_values.append(float(row_values[0]))
y_values.append(float(row_values[1]))
return x_values, y_values
while True:
file_name = input("Choose a file: ")
try:
x_values, y_values = split_columns(file_name)
break
except FileNotFoundError:
print('This file does not exist, try again!')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.