循环Try/Except块直到可以读取文件

2024-09-29 21:45:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在函数中有一个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

Tags: theto函数用户inputfilepressprint
3条回答

你需要打破while循环,这必须在两个地方完成:

  • 读取文件后(当文件正确时)
  • 按下Enter键后。因为我们想结束。你知道吗

此外,还需要在循环中提示问题,以便在每次迭代时再次询问问题,inputFile值用最新的用户输入更新

最后一件事,我认为您的else子句可以删除,因为它永远不会被访问,ifelif抓住了所有的可能性(即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

您的代码中有一个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.")   

这是因为没有给while循环中的inputFile赋值。 它将永远保持同样的价值。。。你知道吗

编辑

一旦将新值赋给循环中的inputFile,请确保在满足退出条件时中断(“user hitsEnter”)

相关问题 更多 >

    热门问题