Python編程:StringIO和BytesIO內(nèi)存中讀寫操作
發(fā)布時間:2021-11-23 點(diǎn)擊數(shù):589
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()