python - “AttributeError:'NoneType'对象没有属性'readline'”的Python原因
问题描述
我正在尝试从每行有 1 个整数的文件中打印整数,并打印它们的总和。一切似乎都工作正常,除非我输入了错误的文件名,循环返回,然后输入正确的文件名。程序仍然输出正确的信息,但随后出现错误:“AttributeError: 'NoneType' object has no attribute 'readline'”。为什么会这样?
def main():
listnums = filetolist()
print(f'numbers in file: {listnums}')
print(f' sum of before mentioned numbers is: {sum(listnums)}')
# opens file
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":
main()
else:
exit()
# converts file to list
def filetolist():
file = openfile()
line = file.readline()
nums = []
linenumber = 1
while line != "":
nums += [verifyint(line, linenumber)]
line = file.readline()
linenumber += 1
file.close()
return nums
# verifies number is an int
def verifyint(num, linenumber):
try:
numint = int(num)
return numint
except ValueError:
print(f'Invalid value on line #{linenumber}')
exit()
main()
解决方案
命中except
block的时候没有return语句,所以这个函数再次None
运行后返回main()
您应该正确地引发错误并使用适当的循环,而不是有效地递归
def filetolist(filename):
with open(filename) as f:
return [int(line.rstrip()) for line in f]
def main():
while True:
filename = input("what is the file named including the file extension?")
try:
listnums = filetolist(filename)
print(f'numbers in file: {listnums}')
print(f' sum of before mentioned numbers is: {sum(listnums)}')
except ValueError, IOError:
again = input('Error! Try again? (y/n)')
if again.lower() != 'y':
break
main()
推荐阅读
- wordpress - 如何从 wordpress 自定义插件的 css 文件?
- android - Android:显示来自 2 个不同来源的 ImageView
- javascript - 编辑动态表中的特定行
- nest-device-access - Google Device Access:在授权期间过滤设备类型
- docker - docker容器内的Webpack“无法解析'./src'”
- javascript - 如何在 webview 中打开 android 默认共享对话框
- ethereum - 为什么 Etherscan 无法验证合约?
- javascript - 如何在本机反应中添加背景阴影或渐变,无论其名称如何
- python - 为什么一个套接字连接会缓冲这么多数据?
- c++ - 在类中使用智能指针和 Tensorflow C API 对象