【问题标题】:AttributeError: 'str' object has no attribute 'readline' While Reading from FileAttributeError:“str”对象在从文件读取时没有属性“readline”
【发布时间】:2018-10-21 05:47:02
【问题描述】:

我运行这段代码:

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'

我不明白我做错了什么?

【问题讨论】:

  • filename 是一个字符串。你应该做file.readline()

标签: python


【解决方案1】:

你在这里调用 filename 是一个字符串而不是 file

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

应该是line=file.readline()

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 2015-02-17
    • 2020-12-18
    • 1970-01-01
    相关资源
    最近更新 更多