这里是新程序员,让我从我拥有的代码开始。
try:
f = input("Please type in the path to your file and press 'Enter'")
file = open(f,'r')
except FileNotFoundError:
f = input("File not found please try again.")
我想要完成的是,如果用户输入了错误的文件,则不断要求用户重试。也许我不应该使用 try/except ?
最佳答案
将该语句嵌入到 while
循环中。 如果文件打开成功,则中断
。
while True:
try:
f = input("Please type in the path to your file and press 'Enter'")
file = open(f, 'r')
break
except FileNotFoundError:
print('File not found')
注意:您可能需要处理其他异常,例如IOError
(即使有一个文件,您可能无法打开它 - 由于权限、文件类型错误,..)
关于python - 如何不断向用户询问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40571629/