【发布时间】:2018-04-08 14:58:09
【问题描述】:
我在一个函数中有一个 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
【问题讨论】:
-
尝试检查修剪后输入的长度而不是
'' -
是的,
while True循环会永远运行,除非你打破它们,这就是重点。 -
读取文件后需要跳出while循环。
标签: python