【问题标题】:Looping a Try/Except block until a file can be read循环一个 Try/Except 块,直到可以读取文件
【发布时间】: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


【解决方案1】:

你需要跳出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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我的回答有帮助吗?如果是,请批准
    【解决方案3】:

    这是因为您没有在 while 循环中为 inputFile 分配新值。 它将永远保持相同的值...

    编辑

    一旦您将在循环中为inputFile 分配一个新值 - 确保在满足退出条件时中断(“用户点击 Enter”)

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多