title: write()-ing an encoded string in Python 3.x
body: <p>I've got a unicode string (s) which I want to write into a file.</p>
  
  <p>In Python 2 I could write:</p>
  
  <pre><code>open('filename', 'w').write(s.encode('utf-8'))
  </code></pre>
  
  <p>But this fails for Python 3. Apparently, s.encode() returns something of type 'bytes', which the write() function does not accept:</p>
  
  <pre><code>TypeError: must be str, not bytes
  </code></pre>
  
  <p>Does anyone know how to port the above code to Python 3?</p>
  
  <p>Edit:</p>
  
  <p>Thanks to all of you who proposed using binary mode! Unfortunately, this causes a problem with the \n characters. Is there any way to achieve the same result I had with Python 2 (namely to encode non-ANSI characters in UTF-8 while keeping the OS-specific rendition of \n)?</p>
  
  <p>Thanks!</p>