I have some simple, working code to read and write files:
openFile = open("filepath", "r")
readFile = openFile.read()
print(readFile)
openFile = open("filepath", "a")
appendFile = openFile.write("\nTest 123")
openFile.close()
But, if I try to read and write the same file, I get errors, or the resulting text is not what I expect. For example:
# I get an error when I use the codes below:
openFile = open("filepath", "r+")
writeFile = openFile.write("Test abc")
readFile = openFile.read()
print(readFile)
openFile.close()
Why can’t I write the code this way? It seems to work if I use a separate open call for the same file:
#I have no problems if I do this:
openFile = open("filepath", "r+")
writeFile = openFile.write("Test abc")
openFile2 = open("filepath", "r+")
readFile = openFile2.read()
print(readFile)
openFile.close()
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
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:
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.