You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序遇无效文件名触发UnboundLocalError而非预期IOError问题

解决你的Python文件读取异常问题

这个问题我太熟悉了!咱们先拆解下你的代码哪里出了问题:

首先贴一下你的原代码:

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

问题根源

当你输入错误文件名时,open()函数会触发IOError,这时候infile变量根本没被赋值——因为open执行失败,直接跳去了except块。而finally块是无论如何都会执行的,这时候调用infile.close(),Python就会报错UnboundLocalError,因为infile这个变量还没被定义出来,自然找不到它。

另外提个小细节:if infile != None:这个判断完全没必要,只要open成功执行,一定会返回有效的文件对象,不会是None,可以直接去掉。

两种修复方案

方案1:初始化变量+判断后关闭

先把infile初始化为None,在finally块里确认它存在后再关闭:

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

方案2:用with语句(更推荐)

Python的with上下文管理器会自动帮你处理文件的打开和关闭——不管代码块是正常结束还是触发异常,都会自动调用close(),完全不需要手动管理,代码更简洁安全:

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

这样修改后,输入错误文件名时,就会正常打印你预期的Error: file not found.,不会再出现UnboundLocalError了。

内容的提问来源于stack exchange,提问作者CodingMans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:32:00