Python编程:StringIO和BytesIO内存中读写操作
发布时间:2021-11-23 点击数:267
StringIO
from io import StringIO #像文件一样写入 f = StringIO() f.write("some words") f.write("other words") print(f.getvalue()) # some wordsother words f.close() # 初始化,然后,像读文件一样读取 f1 = StringIO("code") print(f1.read()) # code f1.close()
BytesIO
from io import BytesIO fb = BytesIO() fb.write("中国".encode("utf-8")) fb.write("美丽".encode("utf-8")) print(fb.getvalue().decode("utf-8")) # 中国美丽 fb.close() # 像读文件一样读取 fb1 = BytesIO("中国".encode("utf-8")) print(fb1.read()) # b'\xe4\xb8\xad\xe5\x9b\xbd' fb1.close()