title: Print unicode string to console OK but fails when redirect to a file. How to fix?
body: <p>I have Python 2.7.1 on a Simplified-Chinese version of Windows XP, and I have a program like this(windows_prn_utf8.py):</p>
  
  <pre><code>#!/usr/bin/env python
  # -*- coding: utf8 -*-
  
  print unicode('\xE7\x94\xB5', 'utf8')
  </code></pre>
  
  <p>If I run it on Windows CMD console, it output the right Chinese character '电' ; however, if I try to redirect the command output to a file. I got error.</p>
  
  <pre><code>D:\Temp&gt;windows_prn_utf8.py &gt; 1.txt
  Traceback (most recent call last):
    File "D:\Temp\windows_prn_utf8.py", line 4, in &lt;module&gt;
      print unicode('\xE7\x94\xB5', 'utf8')
  UnicodeEncodeError: 'ascii' codec can't encode character u'\u7535' in position 0: ordinal not in range(128)
  </code></pre>
  
  <p>I realize there is a missing link here. There should be a way to determine, in case 1.txt is generated, whether the unicode character in 1.txt should be encoded in utf-8 or codepage-936 or other encodings. </p>
  
  <p>Then how to fix it? My preference is to have utf-8 encoding in 1.txt . Thank you.</p>
  
  <p><img src="https://i.stack.imgur.com/5hgdj.png" alt="enter image description here"></p>