我运行以下代码:
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'))
它给了我这个错误属性错误:"str"对象没有属性"读取">
我不明白我做错了什么?
您正在调用文件名,该文件名是字符串而不是此处的文件
file=open(filename, 'r')
line=filename.readline()
应该是line=file.readline((
为了改进代码,我建议您使用代码,除了更具可读性之外,执行速度也更快:
with open(filename, 'r') as file
line=file.readline()