我在函数中有一个try / except块,要求用户输入要打开的文本文件的名称。如果该文件不存在,我希望程序再次询问用户文件名,直到找到它或者用户点击 ENTER 。
现在try / except块只是无限运行。
def getFiles(cryptSelection):
# Function Variable Definitions
inputFile = input("\nEnter the file to " + cryptSelection +\
". Press Enter alone to abort: ")
while True:
if inputFile != '':
try:
fileText = open(inputFile, "r")
fileText.close()
except IOError:
print("Error - that file does not exist. Try again.")
elif inputFile == '':
input("\nRun complete. Press the Enter key to exit.")
else:
print("\nError - Invalid option. Please select again.")
return inputFile
答案 0 :(得分:0)
你需要突破while循环,这必须在2个地方完成:
Enter
键后。因为我们想要结束。此外,您需要在循环内提示问题,以便在每次迭代时再次询问问题,并使用最新的用户输入更新inputFile
值
最后一件事,我认为您的else
子句可以被删除,因为它永远不会被访问,if
和elif
会捕获所有可能性(即inputFile是否有值) )。
def getFiles(cryptSelection):
while True:
inputFile = input("\nEnter the file to %s. Press Enter alone to abort:" % cryptSelection)
if inputFile != '':
try:
fileText = open(inputFile, "r")
fileText.close()
# break out of the loop as we have a correct file
break
except IOError:
print("Error - that file does not exist. Try again.")
else: # This is the Enter key pressed event
break
return inputFile
答案 1 :(得分:0)
您的代码中有一个while True
但没有break
,您可能希望在fileText.close()
之后解决这个问题:
try:
fileText = open(inputFile, "r")
fileText.close()
break
except IOError:
print("Error - that file does not exist. Try again.")
但实际上您应该更改此检查以使用os.path.isfile,如下所示:
import os
def getFiles(cryptSelection):
inputFile = input("\nEnter the file to " + cryptSelection +\
". Press Enter alone to abort: ")
while True:
if inputFile != '':
if os.path.isfile(inputFile):
return inputFile
else:
print("Error - that file does not exist. Try again.")
elif inputFile == '':
input("\nRun complete. Press the Enter key to exit.")
else:
print("\nError - Invalid option. Please select again.")
答案 2 :(得分:-2)
这是因为您没有在inputFile
循环中为while
分配新值。
它将永远保持相同的价值......
修改强>
在循环中为inputFile
分配新值后 - 确保在满足退出条件时突破(&#34; 用户点击输入 < / EM>&#34)