Zakir Hussain
Zakir Hussain

Reputation: 384

How to append to the file using python 3

mean_temp = open("mean_temp.txt",'a+')
mean_temp = mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")
mean_temp.seek(0)
mean_temps = mean_temp.read()
print(mean_temps)

I'm not able to append the text in the file instead it is giving the count in mean_temp where have I gone wrong?

Upvotes: 1

Views: 85

Answers (1)

ingvar
ingvar

Reputation: 4375

mean_temp.write returns written bytes count, so:

mean_temp = open("mean_temp.txt", "a+")
mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")
mean_temp.seek(0)
mean_temps = mean_temp.read()
print(mean_temps)

Also, I recommend using the with statement here:

with open("mean_temp.txt", "a+") as mean_temp:
    mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")
    mean_temp.seek(0)
    data = mean_temp.read()
    print(data)

Upvotes: 1

Related Questions