title: When we write a string to a file, why do we need to care about the encoding?
body: <p>I read <a href="https://docs.python.org/2/howto/unicode.html" rel="nofollow">Python2 Unicode HOWTO</a> and <a href="http://farmdev.com/talks/unicode/" rel="nofollow">Unicode In Python, Completely Demystified</a> to understand Python's Unicode system, and I met some code like this:</p>
  
  <pre><code>f = open('test.txt','w')
  f.write(uni.encode('utf-8'))
  f.close()
  </code></pre>
  
  <p>Why does a unicode <code>str</code> needed to be encoded before it was written into a file?</p>
  
  <p>I know the default encoding is ASCII, so there will be an error because out of range.</p>
  
  <p>But as I write it to file, Isn't it just copying the bits of <code>uni</code> in RAM to file, why does the program need to care about the encoding?</p>