如何修复错误异常以允许重试而无需在Python中进行异常循环

时间:2019-03-29 17:32:17

标签: python exception

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

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

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

1 个答案:

答案 0 :(得分: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