有人可以帮助我在这段代码中获得某种结构吗?我是新来的。错误应同时捕获不存在的文件和不包含由“;”分隔的四部分组成的行的文件。
程序应如下所示:
测验文件名称:hejsan
“这导致输入/输出错误,请重试!”
测验文件名称:namn.csv
“文件的格式不正确。
必须有四个字符串,以;分隔。在文件的每一行中。”
测验文件名称:quiz.csv
其中quiz.csv满足了所有要求!
def get_quiz_list_handle_exceptions():
success = True
while success:
try:
file = input("Name of quiz-file: ")
file2 = open(file,'r')
for lines in range(0,9):
quiz_line = file2.readline()
quiz_line.split(";")
if len(quiz_line) != 4:
raise Exception
except FileNotFoundError as error:
print("That resulted in an input/output error, please try again!", error)
except Exception:
print("The file is not on the proper format. There needs to be four strings, separated by ; in each line of the file.")
else:
success = False
get_quiz_list_handle_exceptions()
答案 0 :(得分:0)
您的代码中存在缩进错误
def get_quiz_list_handle_exceptions():
success = True
while success:
try:
file = input("Name of quiz-file: ")
file2 = open(file,'r')
for lines in range(0,9):
quiz_line = file2.readline()
quiz_line.split(";")
if len(quiz_line) != 4:
raise Exception
except FileNotFoundError as error:
print("That resulted in an input/output error, please try again!", error)
except Exception:
print("The file is not on the proper format. There needs to be four strings, separated by ; in each line of the file.")
else:
success = False
get_quiz_list_handle_exceptions()
答案 1 :(得分:0)
您遇到许多问题:
split
的结果,因此您的长度测试正在测试字符串的长度,而不是分号分隔的分量的数量with
语句,也不关闭文件,因此可以想象文件句柄可能会无限期地保持打开状态(取决于Python解释器)固定代码:
def get_quiz_list_handle_exceptions():
success = True
while success:
try:
file = input("Name of quiz-file: ")
with open(file,'r') as file2: # Use with statement to guarantee file is closed
for lines in range(0,9):
quiz_line = file2.readline()
quiz_line = quiz_line.split(";")
if len(quiz_line) != 4:
raise Exception
# All your excepts/elses were insufficiently indented to match the try
except FileNotFoundError as error:
print("That resulted in an input/output error, please try again!", error)
except Exception:
print("The file is not on the proper format. There needs to be four strings, separated by ; in each line of the file.")
else:
success = False # Fixed indent
get_quiz_list_handle_exceptions()