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'xe4xb8xadxe6x96x87'

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

 

朝闻道
原文地址:https://www.cnblogs.com/wander-clouds/p/8469251.html