StringIO
顾名思义,就是在内存中读写str
要把str
写入StringIO
,需要先创建一个StringIO
, 然后像文件一样写入:
# 写StringIO
from io import StringIO
f = StringIO()
print(f.write('hello'))
print(f.write(' '))
print(f.write('world!'))
print(f.getvalue())
5
1
6
hello world!
getvalue()
方法用于获得写入后的str
读取StringIO
,先用一个str
初始化StringIO
,然后像读文件一样读取:
from io import StringIO
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
Hello!
Hi!
Goodbye!
ByesIO
BytesIO
实现了在内存中读写bytes
,创建一个BytesIO
,然后写入一些bytes
:
from io import BytesIO
f = BytesIO()
print(f.write('中文'.encode('utf-8')))
print(f.getvalue())
6
b'\xe4\xb8\xad\xe6\x96\x87'
值得注意的是,写入的不是str
,而是经过UTF-8
编码的bytes
读取也是一样
from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
f.read()
b'\xe4\xb8\xad\xe6\x96\x87'