title: Mixing read() and write() on Python files in Windows
body: <p>It appears that a <code>write()</code> immediately following a <code>read()</code> on a file opened with <code>r+</code> (or <code>r+b</code>) permissions in Windows doesn't update the file.</p>
  
  <p>Assume there is a file <code>testfile.txt</code> in the current directory with the following contents:</p>
  
  <pre><code>This is a test file.
  </code></pre>
  
  <p>I execute the following code:</p>
  
  <pre><code>with open("testfile.txt", "r+b") as fd:
      print fd.read(4)
      fd.write("----")
  </code></pre>
  
  <p>I would expect the code to print <code>This</code> and update the file contents to this:</p>
  
  <pre><code>This----a test file.
  </code></pre>
  
  <p>This works fine on at least Linux. However, when I run it on Windows then the message is displayed correctly, but the file isn't altered - it's like the <code>write()</code> is being ignored. If I call <code>tell()</code> on the filehandle it shows that the position has been updated (it's <code>4</code> before the <code>write()</code> and <code>8</code> afterwards), but no change to the file.</p>
  
  <p>However, if I put an explicit <code>fd.seek(4)</code> just before the <code>write()</code> line then everything works as I'd expect.</p>
  
  <p>Does anybody know the reason for this behaviour under Windows?</p>
  
  <p>For reference I'm using Python 2.7.3 on Windows 7 with an NTFS partition.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>In response to comments, I tried both <code>r+b</code> and <code>rb+</code> - the <a href="http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="noreferrer">official Python docs</a> seem to imply the former is canonical.</p>
  
  <p>I put calls to <code>fd.flush()</code> in various places, and placing one between the <code>read()</code> and the <code>write()</code> like this:</p>
  
  <pre><code>with open("testfile.txt", "r+b") as fd:
      print fd.read(4)
      fd.flush()
      fd.write("----")
  </code></pre>
  
  <p>... yields the following interesting error:</p>
  
  <pre><code>IOError: [Errno 0] Error
  </code></pre>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>Indirectly that addition of a <code>flush()</code> helped because it lead me to <a href="http://blog.myjotnotes.com/2008/07/08/bizarre-python-file-error/" rel="noreferrer">this post</a> describing a similar problem. If one of the commenters on it is correct, it's a bug in the underlying Windows C library.</p>