python StringIO&BytesIO

StringIO

StringIO就是在内存中读写str


要把str写入StringIO,先创建一个StringIO

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

>>> f.write(' ')

>>> f.write('world!')

>>> print(f.getvalue())
hello world!


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

 

操作二进制数据,需要使用BytesIO

BytesIO实现了在内存中读写bytes

>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))

>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'

写入的不是str,而是经过UTF-8编码的bytes

 

posted @ 2018-02-28 09:21  夜游星  阅读(131)  评论(0编辑  收藏  举报