如何使用python 3追加文件

时间:2017-09-07 16:50:40

标签: python python-3.x

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)

我无法将文字附加到文件中,而是在 mean_temp 中给出计数,哪里出错了?

1 个答案:

答案 0 :(得分:0)

mean_temp.write返回写入的字节数,所以:

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)

我还建议使用"和#34;声明:

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)