Python使用StringIO和BytesIO讀寫內存數據
流讀寫
很多時候,數據讀寫不一定是文件,也可以在內存中讀寫。
1、StringIO:在內存中讀寫str。
要把str寫入StringIO,我們需要先創(chuàng)建一個StringIO,然后,像文件一樣寫入即可:
getvalue()
方法用于獲得寫入后的str。
from io import StringIO f = StringIO() f.write('hello') f.write(' ') f.write('world!') print(f.getvalue()) #hello world!
要讀取StringIO,可以用一個str初始化StringIO,然后,像讀文件一樣讀?。?/p>
from io import StringIO f = StringIO('Hello!\nHi!\nGoodbye!') while True: s = f.readline() if s == '': break print(s.strip()) # Hello! # Hi! # Goodbye!
2、BytesIO:在內存中讀寫bytes
StringIO操作的只能是str,如果要操作二進制數據,就需要使用BytesIO。
BytesIO實現了在內存中讀寫bytes,我們創(chuàng)建一個BytesIO,然后寫入一些bytes:
請注意,寫入的不是str,而是經過UTF-8編碼的bytes。
from io import BytesIO f = BytesIO() f.write('中文'.encode('utf-8')) print(f.getvalue()) # b'\xe4\xb8\xad\xe6\x96\x87'
和StringIO類似,可以用一個bytes初始化BytesIO,然后,像讀文件一樣讀?。?/p>
from io import BytesIO f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87') f.read().decode('utf-8') # '中文'
3、小結
StringIO和BytesIO是在內存中操作str和bytes的方法,使得和讀寫文件具有一致的接口。
到此這篇關于Python使用StringIO和BytesIO讀寫內存數據的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。