title: writing bytes to file in python
body: <p>I am writing bittorrent client. It can download pieces from peers, but I can't make it write pieces to files correctly. The problem is the encoding. Because of the wrong encoding client is writing wrong bytes to file. I have found encoding called "unicode_internal". It seems to be correct one but the problem didn't go away. Despite the constant piece size(16384 bytes) sometimes the file size increases by 16386 or so.
  Here's how I write pieces to file. Nothing special.</p>
  
  <pre><code>with open(path, 'a', encoding='unicode_internal') as f:
      f.seek(offset, 0)
      f.write(data.decode('unicode_internal'))
  </code></pre>
  
  <p>I tryed to open file in 'rb' mode but it doesn't help.
  Part of the stdout from working client:</p>
  
  <pre><code>piece size: 16384
  sum of pieces lengths: 49152
  filesize: 49152
  
  piece size: 16384
  sum of pieces lengths: 65536
  filesize: 65536
  
  piece size: 16384
  sum of pieces lengths: 81920
  filesize: 81922 #Here it is. Size increased by 16386 bytes. The piece size is 16384
  
  piece size: 16384
  sum of pieces lengths: 98304
  filesize: 98306
  </code></pre>
  
  <p>What am I doing wrong?</p>