我在函数中有一个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循环,这必须在两个地方完成:
Enter
键后。因为我们想结束。你知道吗此外,还需要在循环中提示问题,以便在每次迭代时再次询问问题,
inputFile
值用最新的用户输入更新最后一件事,我认为您的
else
子句可以删除,因为它永远不会被访问,if
和elif
抓住了所有的可能性(即inputFile是否有值)。你知道吗您的代码中有一个
while True
,但没有break
,您可能希望在fileText.close()
之后中断,如下所示:但你真的应该把这张支票改成os.path.isfile文件像这样:
这是因为没有给
while
循环中的inputFile
赋值。 它将永远保持同样的价值。。。你知道吗编辑
一旦将新值赋给循环中的
inputFile
,请确保在满足退出条件时中断(“user hitsEnter”)相关问题 更多 >
编程相关推荐