开发者

Opening a file for append

I just had a passing thought and figured what better place to ask then right here. Out of curiosity, does anyone know if opening a file for append, like this:

file_name = "abc"
file_handle = open(file_name,"a")

Is essentially the same as opening a file for writing and seeking to the end:

file_name = "abc"
file_ha开发者_JS百科ndle = open(file_name,"w")
file_handle.seek(0,2) # 0 for offset, 2 for end-of-file

I'm just wondering if opening a file for append is essentially doing the second block, open for write followed by a seek to the end of the file, behind the scenes.


After playing a bit in my terminal, I can say what the differences are on ubuntu linux 11.04 using python 2.7.1.

Opening with 'w' truncates (i.e. erases the contents of) the file as soon as it's opened. In other words, just opening the file with open('file.txt', 'w') and exiting leaves behind an empty file.

Opening with 'a' leaves the contents of the file intact. So opening with open('file.txt', 'a') and exiting leaves the file unchanged.

This also applies to the update options for open. The command open('file.txt', 'w+') will leave an empty file, while the commands open('file.txt', 'r+') and open('file.txt', 'a+') will leave unchanged files.

The difference between the options 'r+' and 'a+' is the behavior that others have suggested. The option 'r+' lets you write anywhere in the file, while 'a+' forces all writes to the end of the file, regardless of where you set the file's current position to be.

If you'd like to look into it more, according to the python documentation the function open accepts modes similar to the fopen function of C's stdio.


Not really. Using append forces any writes to go to the end of the file, where you can seek to another location with a write.


"W" will delete the content data and then seek to the final position. So, you'll end with an empty file with a pointer at BOF and not EOF. Use "A" to keep old data.


It depends on system you're working on; opening a file with append flag often means you're going to write at the end of file regardless of the write pointer position. In other words, it could mean your OS has to perform seek to the end of the file before every write or just seek the pointer to the end after opening. You can easily check how it works under you environment, but the only guaranteed behaviour is seeking to the end after opening.

EDIT: As other people pointed out, w flag effectively truncates the file. If you would like to open it for updating without removing current content, you would have to use r+ flag (but then reading would be allowed which is not true for a).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜