python3 下的文件输入输出特性以及如何覆盖文件内容和接下去输入

  今天碰到了一个非常有意思的python特性。本来我是想打开一个文件,在文件的末尾接下去输入一些内容的,代码如下:

f = open('test.txt', 'r+')
f.write(content)
f.close()

  结果发现无论我写什么东西,content的内容总是会从文件开头写入,并且覆盖掉原来的内容。查了官方文档,也不知道应该怎么做。

  但偶然间我发现了接到末尾写入的方法,代码如下:

f = open('test.txt', 'r+')
f.read()
f.write(content)
f.close()

  没错,只是添加了一行f.read(),之后你的write函数就会自动接到末尾进行写入了。去翻了下官方文档,貌似没有提及这个。

read(size)

Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.

 

write(s)

Write the string s to the stream and return the number of characters written.

 

posted @ 2015-12-07 12:51  Xander-Hang  阅读(4664)  评论(5编辑  收藏  举报