Beginner Python: Reading and writing to the same file

Updated Response:

This seems like a bug specific to Windows – http://bugs.python.org/issue1521491.

Quoting from the workaround explained at http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html

the effect of mixing reads with writes on a file open for update is entirely undefined unless a file-positioning operation occurs between them (for example, a seek()). I can’t guess what you expect to happen, but seems most likely that what you intend could be obtained reliably by inserting

fp.seek(fp.tell())

between read() and your write().

My original response demonstrates how reading/writing on the same file opened for appending works. It is apparently not true if you are using Windows.

Original Response:

In ‘r+’ mode, using write method will write the string object to the file based on where the pointer is. In your case, it will append the string “Test abc” to the start of the file. See an example below:

>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\n'
>>> f.write("foooooooooooooo")
>>> f.close()
>>> f=open("a","r+")
>>> f.read()
'Test abc\nfasdfafasdfa\nsdfgsd\nfoooooooooooooo'

The string “foooooooooooooo” got appended at the end of the file since the pointer was already at the end of the file.

Are you on a system that differentiates between binary and text files? You might want to use ‘rb+’ as a mode in that case.

Append ‘b’ to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the ‘b’ has no effect. http://docs.python.org/2/library/functions.html#open

Leave a Comment