【发布时间】:2016-05-26 07:20:23
【问题描述】:
我是网站和 python 的新手。我正在学习如何使用 try-except 处理错误。我要求输入以打开文件并搜索一行。这是我现在拥有的程序。它主要工作......
try:
file_str = input("Open what file:")
input_file = open(file_str) # potential user error
find_line_str = input("Which line (integer):")
find_line_int = int(find_line_str) # potential user error
line_count_int = 1
for line_str in input_file:
if line_count_int == find_line_int:
print("Line {} of file {} is {}".format(find_line_int, file_str,line_str))
break
line_count_int += 1
else: # get here if line sought doesn't exist
print("Line {} of file {} not found".format(find_line_int,file_str))
input_file.close()
except IOError:
while True:
file_str = input("That file was not found. Please try again:")
except ValueError:
find_line_str = input("Invalid line value. Please try again:")
print("End of the program")
最初,如果出现错误,它会说“无效输入,程序结束”现在我试图让程序继续要求输入,直到用户正确为止。
通过我在 except IOError 中放入的 while 循环,即使我输入了有效的文件名,它也会永远循环。如果我只是要求输入,它会在输入后结束程序。
如何让它在收到有效输入后返回并运行 for 循环?几个小时以来,我一直在努力解决这个问题,我非常感谢您的帮助。
【问题讨论】:
-
while 将在下一行循环。
标签: python python-3.x