gpt4 book ai didi

python - 属性错误: 'str' object has no attribute 'readline' While Reading from File

转载 作者:行者123 更新时间:2023-12-01 01:30:35 25 4
gpt4 key购买 nike

我运行这段代码:

file=open(filename, 'r')

line=filename.readline()
totallines=0
total=0
while line != "":
amount=float(line)
print(format(amount, '.2f'))
line=filename.readline()
totallines+=1
total+=amount
avg=total/totallines
print("The average of the numbers is", format(avg, '.2f'))

它给了我这个错误AttributeError: 'str' object has no attribute 'read'

我不明白我做错了什么?

最佳答案

您正在调用文件名,它是一个字符串,而不是这里的文件

file=open(filename, 'r')
line=filename.readline()

应该是line=file.readline()

为了改进代码,我建议您使用withas,它们的执行速度更快,而且更多可读性::

with open(filename, 'r') as file
line=file.readline()

关于python - 属性错误: 'str' object has no attribute 'readline' While Reading from File,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52912447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com