How can I open a file with a known encoding in both Python2 and 3?

When opening a file known as utf-8 to a script that should be compatible with Py2 and 3. Is there a better way to do this than this:

if sys.version_info < (3, 0):
    long_description = open('README').read()
else:
    long_description = open('README', encoding='utf-8').read()

      

The call open('README').read()

to Python3.x throws a coding error for systems for which it defaults ascii

.

+3


source to share


2 answers


You can use a function io.open

that is built open()

in Python 3.



from io import open
long_description = open('README', encoding='utf-8').read()

      

+2


source


Use codecs.open

. It is cross-python compatible:



import codecs
long_description = codecs.open('README', encoding='utf-8').read()

      

+2


source







All Articles