簡體   English   中英

AttributeError:從文件讀取時,“ str”對象沒有屬性“ readline”

[英]AttributeError: 'str' object has no attribute 'readline' While Reading from File

我運行以下代碼:

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'對象沒有屬性'read'

我不明白我在做什么錯?

您正在調用的文件名是字符串而不是文件

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

應該是line = file.readline()

為了提高代碼我建議 它是執行速度更快 ,以及除了是更可讀的使用方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM