After reading some posts, it seems like you can open a file for both reading and writing with the mode of ‘r+’ or ‘w+’. However, trying to use these modes always give me weird results:
- If I use ‘r+’, call file.read(), and then call file.write(‘str’),
there’ll be an error of “IOError: [Errno 0] Error” - If I use ‘r+’, call file.write(‘str’), and then call file.read(),
it’ll return unexpected and very long content(looks like the inside
of some object) - If I use ‘w+’, calling file.read() will return empty string
What I’m trying to do is open a file, read the content, modify it, and write back. Currently I’m opening it with ‘r’, change the content, and open it again with ‘w’ and write back. Is this a good way of doing it?
There’s an example at http://snipt.org/zglJ0
I’m using window 7 and python 2.7.2
You have to
flush()when switching between reading and writing a file that’s been opened in an update mode. Or I think you can alsoseek(). This is caused by some weird behavior in the Windows file implementation in Python 2.x; they fixed it in 3.x.