问题
When opening a file known to be utf-8 on a script that needs to be Py2 & 3 compatible. Is there a nicer way to do it than this:
if sys.version_info < (3, 0):
long_description = open('README').read()
else:
long_description = open('README', encoding='utf-8').read()
Calling open('README').read()
on Python3.x causes encoding error for systems that default to ascii
.
回答1:
You could use the io.open
function, which is the built-in open()
in Python 3.
from io import open
long_description = open('README', encoding='utf-8').read()
回答2:
Use codecs.open. It's cross-Python compatible:
import codecs
long_description = codecs.open('README', encoding='utf-8').read()
来源:https://stackoverflow.com/questions/45537244/how-to-open-a-file-with-a-known-encoding-on-both-python2-and-3