1

I run this code:

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'))

and it gives me this error AttributeError: 'str' object has no attribute 'read'

I dont understand what Im doing wrong?

1
  • 3
    filename is a string. you should do file.readline() Commented Oct 21, 2018 at 5:53

1 Answer 1

3

You are calling filename which is a string instead of file in here

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

Should be line=file.readline()

In order to improve the code I suggest you use with and as which is faster in execution as well besides being more readable:

with open(filename, 'r') as file
line=file.readline()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.