Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python open('file','r+') giving weird result

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

like image 527
Xun Yang Avatar asked Feb 03 '12 15:02

Xun Yang


1 Answers

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.

like image 66
kindall Avatar answered Sep 27 '22 19:09

kindall