A problem when one tries to add a text of little size: it remains in the buffer, that keeps the text before the real writing is done after receiving more data.
So, to be sure to write really, do as it is described in the doc concerning os.fsync()
and flush()
By the way, it is better to use the with
statement.
And it's still more better to use binary mode. In your case, there shouldn't be a problem because you just add text after the reading and just use seek(o,o)
. But when one wants to move correctly the file's pointer into the bytes of the file, it is absolutely necessary to use binary mode [ the 'b'
in open(filename, 'rb+')
]
I personnaly never use 'a+'
, I've never understood what are its effects.
from sys import argv
from os import fsync
script, filename = argv
with open(filename, 'rb+') as f:
print("The contents of %s are:") % filename
print f.read()
f.seek(0,2)
txt = raw_input("What would you like to add? ")
f.write(txt)
f.flush()
fsync(f.fileno())
f.seek(0,0)
print("The new contents are:")
print f.read()