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_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.

ideasman42
  • 42,413
  • 44
  • 197
  • 320

2 Answers2

2

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

import codecs
long_description = codecs.open('README', encoding='utf-8').read()
randomir
  • 17,989
  • 1
  • 40
  • 55
2

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()
cdonts
  • 9,304
  • 4
  • 46
  • 72