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

Python输错文件名再输正确时出现AttributeError:'NoneType'无readline属性的原因

错误原因分析
  • 根本原因是openfile函数的重试逻辑存在调用栈嵌套问题,函数返回值不符合预期:
    1. 首次输入错误文件名触发IOError后,你选择重试时,代码直接调用了main()开启了新的程序执行流程,这一轮新流程输入正确文件名后会正常执行完所有输出逻辑,和你看到的“能输出正确结果”的现象一致。
    2. 但新的main()执行结束后,程序会回到最开始的openfile调用上下文,而重试分支的代码没有给openfile函数设置返回值,因此最初的openfile调用会默认返回None。
    3. 回到最初的filetolist函数执行逻辑时,file变量被赋值为None,执行file.readline()自然就会抛出AttributeError: 'NoneType' object has no attribute 'readline'的错误。
修复方案
  • 不要在openfile的重试分支里直接调用main(),改为重试调用openfile本身,正确返回读取到的文件对象即可,修改后的openfile代码参考:
def openfile():
    try:
        file = open(input("what is the file named including the file extension?"), "r")
        return file
    except IOError:
        tryagain = input("File could not be found \n" + "if you would like try again type 1 and press enter, to exit press enter")
        if tryagain == "1":
            # 这里直接返回重试openfile的结果,不要调用main
            return openfile()
        else:
            exit()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:15:03