Change to recognized encoding when reading a text file?
<p>When a text file is open for reading using (say) UTF-8 encoding, is it possible to change encoding during the reading?</p>

<p><strong>Motivation:</strong> It hapens that you need to read a text file that was written using non-default encoding. The text format may contain the information about the used encoding. Let an HTML file be the example, or XML, or ASCIIDOC, and many others. In such cases, the lines above the encoding information are allowed to contain only ASCII or some default encoding.</p>

<p>In Python, it is possible to read the file in binary mode, and translate the lines of <code>bytes</code> type to <code>str</code> on your own. When the information about the encoding is found on some line, you just switch the encoding to be used when converting the lines to unicode strings.</p>

<p>In Python 3, text files are implemented using <code>TextIOBase</code> that defines also the <code>encoding</code> attribute, the <code>buffer</code>, and other things.</p>

<p>Is there any nice way to change the encoding information (used for decoding the <code>bytes</code>) so that the next lines would be decoded in the wanted way? </p>

<p>Classic usage is:</p>

<ul>
<li>Open the file in binary format (bytes string)</li>
<li>read a chunk and guess the encoding (For instance with a simple scanning or using RegEx)</li>
</ul>

<p>Then:</p>

<ul>
<li>close the file and re-open it in text mode with the found encoding
Or</li>
<li>move to the beginning: seek(0), read the whole content as a bytes string then decode the content using the found encoding.</li>
</ul>

<p>See this example: <a href="http://code.activestate.com/recipes/363841-detect-character-encoding-in-an-xml-file/" rel="nofollow">Detect character encoding in an XML file (Python recipe)</a>
<em>note:</em> the code is a little old, but useful.</p>

python file python-3.x encoding