title: Write to UTF-8 file in Python
body: <p>I'm really confused with the <code>codecs.open function</code>. When I do:</p>
  
  <pre><code>file = codecs.open("temp", "w", "utf-8")
  file.write(codecs.BOM_UTF8)
  file.close()
  </code></pre>
  
  <p>It gives me the error</p>
  
  <blockquote>
    <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position
    0: ordinal not in range(128)</p>
  </blockquote>
  
  <p>If I do:</p>
  
  <pre><code>file = open("temp", "w")
  file.write(codecs.BOM_UTF8)
  file.close()
  </code></pre>
  
  <p>It works fine.</p>
  
  <p><strong>Question</strong> is why does the first method fail? And how do I insert the bom?</p>
  
  <p>If the second method is the correct way of doing it, what the point of using <code>codecs.open(filename, "w", "utf-8")</code>?</p>