title: Changing the “locale preferred encoding” in Python 3 in Windows
body: <p>I'm using Python 3 (recently switched from Python 2). My code usually runs on Linux but also sometimes (not often) on Windows. According to Python 3 documentation for <a href="https://docs.python.org/3/library/functions.html#open" rel="noreferrer"><code>open()</code></a>, the default encoding for a text file is from <code>locale.getpreferredencoding()</code> if the <code>encoding</code> arg is not supplied. I want this default value to be <code>utf-8</code> for a project of mine, no matter what OS it's running on (currently, it's always UTF-8 for Linux, but not for Windows). The project has many many calls to <code>open()</code> and I don't want to add <code>encoding='utf-8'</code> to all of them. Thus, I want to change the locale's preferred encoding in Windows, as Python 3 sees it.</p>
  
  <p>I found a previous question
  "<a href="https://stackoverflow.com/questions/11514414/changing-the-locale-preferred-encoding">Changing the &quot;locale preferred encoding&quot;</a>", which has an accepted answer, so I thought I was good to go. But unfortunately, neither of the suggested commands in that answer and its first comment work for me in Windows. Specifically, that accepted answer and its first comment suggest running <code>chcp 65001</code> and <code>set PYTHONIOENCODING=UTF-8</code>, and I've tried both. Please see transcript below from my cmd window:</p>
  
  <pre><code>&gt; py -i
  Python 3.4.3 ...
  &gt;&gt;&gt; f = open('foo.txt', 'w')
  &gt;&gt;&gt; f.encoding
  'cp1252'
  &gt;&gt;&gt; exit()
  
  &gt; chcp 65001
  Active code page: 65001
  
  &gt; py -i
  Python 3.4.3 ...
  &gt;&gt;&gt; f = open('foo.txt', 'w')
  &gt;&gt;&gt; f.encoding
  'cp1252'
  &gt;&gt;&gt; exit()
  
  &gt; set PYTHONIOENCODING=UTF-8
  
  &gt; py -i
  Python 3.4.3 ...
  &gt;&gt;&gt; f = open('foo.txt', 'w')
  &gt;&gt;&gt; f.encoding
  'cp1252'
  &gt;&gt;&gt; exit()
  </code></pre>
  
  <p>Note that even after both suggested commands, my opened file's encoding is still <code>cp1252</code> instead of the intended <code>utf-8</code>.</p>