【问题标题】:How to fix error exception to allow for retries without the exception looping in Python如何修复错误异常以允许重试而不在 Python 中循环异常
【发布时间】:2019-03-29 17:32:17
【问题描述】:

我正在尝试在 Python 2.7 中编写错误处理,以便在用户输入文件名后引发 IOError 异常。

我在互联网上尝试了几种解决方案,包括:

How to retry after exception? Get a Try statement to loop around until correct value obtained

这是我的原始代码:

while True: 
    try:
        with open (userFile, 'r') as txtFile:
            for curLine in txtFile:
                curLine = curLine.rstrip("\n\r")
                idList.append(curLine)
    except IOError:
        print("File does not exist")

每当引发 IOError 异常时,它都会进入一个无限循环,一遍又一遍地打印“文件不存在”。在我通过添加范围来限制尝试的情况下,它会通过该范围,一遍又一遍地打印,然后退出脚本。有谁知道为什么在引发异常时它会一直循环?

【问题讨论】:

    标签: python exception


    【解决方案1】:

    如果您将单独的关注点拆分为函数,这将容易得多,即 (i) 如果文件不存在则警告用户,以及 (ii) 将文件的内容读入行列表:

    def read_file(f):
        # you can't read a file line-by-line and get line endings that match '\n\r'
        # the following will match what your code is trying to do, but perhaps not 
        # what you want to accomplish..?
        return f.read().split("\n\r")  # are you sure you haven't switched these..?
    
    def checked_read_file(fname):
        try:
            with open(fname, 'rb') as fp:  # you'll probably need binary mode to read \r
                return read_file(fp)
        except IOError:
            print("File does not exist")
            return False
    

    然后你可以编写你的while循环:

    while True:
        result = checked_read_file(user_file)
        if result is not False:  # this is correct since the empty list is false-y
            break
        user_file = input("Enter another filename: ")  # or user_file = raw_input("...: ") if you're on Python 2
    
    # here result is an array of lines from the file
    

    【讨论】:

    • 感谢您的意见。这在第一次检查成功时确实有效,但是当引发异常 IOError 并要求用户重试时,它总是会出现以下错误:Traceback (most recent call last): File ".\testing_while_loop.py", line 23, in <module> userFile = input("Enter another filename: ") File "<string>", line 1, in <module> NameError: name 'test_file' is not defined。我对使用函数不是很熟悉,所以我假设错误在那里,但我还没有找到它。你有什么见解吗?
    • 如果您使用的是 Python 2,则需要将 input 重命名为 raw_input
    • 我当然错过了。是的,由于某些模块的使用,我仍在使用 Python 2.7。一旦我将input 更改为raw_input,它就可以完美运行。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 2016-06-22
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多