How to open a file with a known encoding on both Python2 and 3?

心已入冬 提交于 2019-12-10 20:32:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!