开发者

Why does my file get overwritten?

开发者 https://www.devze.com 2023-04-01 18:54 出处:网络
When using this code in python: f = open(\'ping.log\', \'r+\') f.write(\"[\"+time.ctime()+\"]\"+\"Status\")

When using this code in python:

 f = open('ping.log', 'r+')
 f.write("["+time.ctime()+"]"+"Status")
 f.close()

My file always gets overwritten. And only has one 开发者_如何学JAVAline in it, like this:

[Fri Sep 02 16:30:56 2011]Status

Why is it getting overwritten?


It's failing because you are effectively recreating the file each time as you are overwriting the first N bytes every time. If you wrote less bytes you'd see the "old" information still there.

You need to open the file for "append"

'a' opens the file for appending

Source


r+ sets the initial file pointer to the beginning. Either seek to the end or use a mode.


Check this question. Open the file with the "a" mode:

f = open("ping.log","a")
...


http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

so use

f = open('ping.log', 'a')
f.write("["+time.ctime()+"]"+"Status")
f.close()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号