python StringIO和ByteIO

一、StringIO

1、作用:在内存在读写str

# 导入模块
from io import StringIO
# 实例化StringIO对象
str_io = StringIO()
# 向内存中写入str
str_io.write("Hello World!")
# 从内存中取值
new_str = str_io.getvalue()
print(new_str)
from io import StringIO
# 可以用一个str初始化StringIO
s1 = "你好
世界
宇宙"
str_io = StringIO("你好
世界
宇宙")
while 1:
    for i in str_io:
        print(i, end="")

从内存中读取str,可以和读取文件一样

f = StringIO("你好
世界
宇宙")

二、ByteIO

作用:在内存在读取bytes,如图片、视频等

# 导入模块
from io import BytesIO
# 实例化对象
byte_io = BytesIO()
byte_io.write("世界".encode("utf-8"))
# 全部读取
print(byte_io.getvalue().decode("utf-8"))

同理,也可以和操作文件一样读取内存的bytes

from io import BytesIO
f = BytesIO(b'xe4xb8x96xe7x95x8c')
data = f.read()
print(data)
原文地址:https://www.cnblogs.com/wt7018/p/11312962.html