Python IO编程

StringIO和BytesIO

StringIO就是在内存中读写str,要把str写入StringIO,需要先创建一个StringIO,然后,像文件一样写入即可

from io import StringIO
f = StringIO()
f.write('hello')

getvalue()方法用于获得写入后的str

BytesIO

StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO

BytesIO实现了在内存中读写bytes,创建一个BytesIO,然后写入一些bytes

from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
原文地址:https://www.cnblogs.com/liushoudong/p/13601728.html