当我尝试打开无效的文件名时出现UnboundLocalError

时间:2019-11-09 01:38:42

标签: python file

我编写了一个程序,该程序可以使用文件名并返回数字,并且在正确输入文件名后可以正常工作,但是当我尝试故意写错文件名而不是给我“错误:文件不正确”时找到”,它会说:

def getFile(fileName):
lines = []
try:
    infile = open(fileName, 'r')
    if infile != None:
        for line in infile:
         lines.append(line)

except IOError:
    print('Error: file not found.')

finally:
    infile.close()
return lines

1 个答案:

答案 0 :(得分:1)

如果open引发了异常,则永远不会声明局部变量infile,更不用说赋值了,因此在infile.close()块中调用finally的尝试将引发您在此处看到的UnboundLocalError。您可以通过用一些特殊的未初始化值(例如infile)声明None并像这样进行显式检查来对此问题进行“修复”:

def getFile(fileName):
    lines = []
    infile = None
    try:
        infile = open(fileName, 'r')
        for line in infile:
            lines.append(line)
    except IOError:
        print('Error: file not found.')
    finally:
        if infile is not None:
            infile.close()
    return lines

或者,由于文件对象为are context managers,因此您可以编写如下内容:

def getFile(fileName):
    lines = []
    try:
        with open(fileName, 'r') as infile:
            for line in infile:
                lines.append(line)
    except IOError:
        print('Error: file not found.')
    return lines

...将确保infile以句法简洁和结构化的方式关闭。


请注意,如果失败,open会引发OSError(例如FileNotFoundError)而不是返回None,因此您现有的检查是多余的。

此外,在遍历文件而不是最初打开文件时可能会引发IOError,因此在这种情况下打印的错误消息可能不正确。

最后,由于infile是可迭代的,因此您可以使用constructor that accepts an iterable directly轻松地从其迭代构造一个列表,如下所示:

return list(infile)