tags:

views:

96

answers:

1

According to the documentation of open function 'a' means appending, which on some Unix systems means that all writes append to the end of the file regardless of the current seek position.

Will 'a+' allow random writes to any position in the file on all systems?

+2  A: 

On my linux system with Python 2.5.2 writes to a file opened with 'a+' appear to always append to the end, regardless of the current seek position.

Here is an example:

import os

if __name__ == "__main__":

    f = open("test", "w")
    f.write("Hello")
    f.close()

    f = open("test", "a+")
    f.seek(0, os.SEEK_SET)
    f.write("Goodbye")
    f.close()

On my system (event though I seeked to the beginning of the file) this results in the file "test" containing:

HelloGoodbye

The python documentation says that the mode argument is the same as stdio's.

The linux man page for fopen() does say that (emphasis added):

Opening a file in append mode (a as the first character of mode) causes all subsequent write operations to this stream to occur at end-of-file, as if preceded by an

fseek(stream,0,SEEK_END);

call.

My stdio reference says that appending a '+' to the mode (i.e. 'a+') means that the stream is opened for input and output. However before switching between input and output a call must be made to explicitly set the file position.

So adding the '+' doesn't change the fact that on some systems writes for a file opened in 'a' or 'a+' mode will always append to the end of the file.

Karl Voigtland
Thanks, it seems that I need to check if file exists and open with different file modes :(
Piotr Czapla