如何在 Python2 和 3 上打开具有已知编码的文件? [英] How to open a file with a known encoding on both Python2 and 3?
本文介绍了如何在 Python2 和 3 上打开具有已知编码的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在需要 Py2 & 的脚本上打开已知为 utf-8 的文件时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()
在 Python3.x 上调用 open('README').read()
会导致默认为 ascii
的系统出现编码错误.
Calling open('README').read()
on Python3.x causes encoding error for systems that default to ascii
.
推荐答案
你可以使用 io.open
函数,它是内置的 open()
Python 3.
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()
这篇关于如何在 Python2 和 3 上打开具有已知编码的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文