首页 > 解决方案 > 如何修复错误异常以允许重试而不在 Python 中循环异常

问题描述

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

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

异常后如何重试? 获取一个 Try 语句循环,直到获得正确的值

这是我的原始代码:

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

标签: pythonexception

解决方案


如果您将单独的关注点拆分为函数,这将容易得多,即(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

推荐阅读