StringIO
StringIO 是指在内存中操作字符串
from io import StringIO
# 将字符串写入内存中
f = StringIO()
f.write('hello')
f.write(' ')
f.write('python')
print(f.getvalue()) # hello python
# 从内存中读取字符串
f = StringIO('hello\npython\nStringIO')
while True:
content = f.readline()
if len(content) == 0:
break
print(content.strip())
BytesIO
BytesIO 是指在内存中操作二进制
from io import BytesIO
# 将二进制数据写入内存
f = BytesIO()
f.write('哈喽'.encode('utf-8'))
print(f.getvalue().decode('utf-8'))
# 读取内存中二进制数据
f = BytesIO('哈喽'.encode('utf-8'))
content = f.read().decode('utf-8')
print(content)