[英]Decoding a File-like object open in binary mode
在python中,给定以二进制模式打开的类似文件的对象,将其转换为UTF8解码的类似文件的对象而不将所有内容加载到内存的最佳方法是什么?
You can get the StreamReader for a particular encoding and pass it the stream. 您可以获取特定编码的StreamReader并将其传递给流。 It will only return completely decoded code points.
它只会返回完全解码的代码点。
#coding:utf8
import codecs
import io
# A file-like binary stream.
data = io.BytesIO('我是美国人。\n你是中国人。\n'.encode('utf8'))
# Get the UTF-8 StreamReader class and instantiate it on the data.
f = codecs.getreader('utf8')(data)
print(f.read(2))
f.seek(0)
for line in f:
print(line,end='')
Output: 输出:
我是
我是美国人。
你是中国人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.