Skip to content Skip to sidebar Skip to footer

How To Open A File With A Known Encoding On Both Python2 And 3?

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_descri

Solution 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()

Solution 2:

Use codecs.open. It's cross-Python compatible:

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

Post a Comment for "How To Open A File With A Known Encoding On Both Python2 And 3?"