Python输错文件名再输正确时出现AttributeError:'NoneType'无readline属性的原因
错误原因分析
- 根本原因是
openfile函数的重试逻辑存在调用栈嵌套问题,函数返回值不符合预期:- 首次输入错误文件名触发IOError后,你选择重试时,代码直接调用了
main()开启了新的程序执行流程,这一轮新流程输入正确文件名后会正常执行完所有输出逻辑,和你看到的“能输出正确结果”的现象一致。 - 但新的
main()执行结束后,程序会回到最开始的openfile调用上下文,而重试分支的代码没有给openfile函数设置返回值,因此最初的openfile调用会默认返回None。 - 回到最初的
filetolist函数执行逻辑时,file变量被赋值为None,执行file.readline()自然就会抛出AttributeError: 'NoneType' object has no attribute 'readline'的错误。
- 首次输入错误文件名触发IOError后,你选择重试时,代码直接调用了
修复方案
- 不要在
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
相关产品推荐
相关产品推荐

