Python使用StringIO和BytesIO讀寫內(nèi)存數(shù)據(jù)
流讀寫
很多時候,數(shù)據(jù)讀寫不一定是文件,也可以在內(nèi)存中讀寫。
1、StringIO:在內(nèi)存中讀寫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:在內(nèi)存中讀寫bytes
StringIO操作的只能是str,如果要操作二進(jìn)制數(shù)據(jù),就需要使用BytesIO。
BytesIO實現(xiàn)了在內(nèi)存中讀寫bytes,我們創(chuàng)建一個BytesIO,然后寫入一些bytes:
請注意,寫入的不是str,而是經(jīng)過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、小結(jié)
StringIO和BytesIO是在內(nèi)存中操作str和bytes的方法,使得和讀寫文件具有一致的接口。
到此這篇關(guān)于Python使用StringIO和BytesIO讀寫內(nèi)存數(shù)據(jù)的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python腳本實現(xiàn)mp4中的音頻提取并保存在原目錄
這篇文章主要介紹了python腳本實現(xiàn)mp4中的音頻提取并保存在原目錄,本文給大家通過實例代碼介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02