擅长:python、mysql、java
<p>您可以使用<a href="https://docs.python.org/3/library/codecs.html?highlight=codecs#codecs.open" rel="nofollow">codecs module</a>来编写“版本不可知”代码:</p>
<blockquote>
<p>Underlying encoded files are always opened in binary mode. No automatic conversion of <code>'\n'</code> is done on reading and writing. The mode argument may be any binary mode acceptable to the built-in <code>open()</code> function; the <code>'b'</code> is automatically added.</p>
</blockquote>
<pre><code>import codecs
with codecs.open('foo', mode='r', encoding='utf8') as f:
# python2: u'foo\r\n'
# python3: 'foo\r\n'
f.readline()
</code></pre>