Python open ('file', 'r +') giving strange result

After reading some messages, it seems that you can open the file for reading and writing in "r +" or "w +" mode. However, attempts to use these modes always give me strange results:

  • If I use 'r +', call file.read () and then call file.write ('str'), there will be an error "IOError: [Errno 0] Error"
  • If I use 'r +', call file.write ('str') and then call file.read (), it will return unexpected and very long content (looks like inside an object)
  • If I use 'w +', calling file.read () will return an empty string

What I'm trying to do is open a file, read the contents, modify it and write. Currently, I open it with "r", change the content and open it again with "w" and write it back. Is this a good way to do this?

Example: http://snipt.org/zglJ0

I am using window 7 and python 2.7.2

+5
source share
1 answer

When switching between reading and writing a file that was opened in update mode, you should flush(). Or I think you can too seek(). This is caused by some strange behavior in the implementation of a Windows file in Python 2.x; they fixed it at 3.x.

+5
source

All Articles