5
votes

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:

  1. If I use 'r+', call file.read(), and then call file.write('str'), there'll be an error of "IOError: [Errno 0] Error"
  2. 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)
  3. 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

1
Could you share a code snippet that demonstrates the problem? - Joachim Isaksson
The three experiments above are all closed by file.close(). However, it seems doing both read() and write() in the same experiment (not calling close() in between) will leads to weird result. - Xun Yang
Is this on both windows and linux? - tMC
Can you please post a code snippet of what you're attempting to do? I've written a small piece of code and it functions exactly as expected. Also, what version of Python are you using? - pri0ritize
snipt.org/zglJ0 I'm using windows and python 2.7.2 (Sorry I put the code wrong, now it's what causing the problem :)) - Xun Yang

1 Answers

5
votes

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 also seek(). This is caused by some weird behavior in the Windows file implementation in Python 2.x; they fixed it in 3.x.