不少時候,數據讀寫不必定是文件,也能夠在內存中讀寫。ui
StringIO顧名思義就是在內存中讀寫str。編碼
要把str寫入StringIO,咱們須要先建立一個StringIO,而後,像文件同樣寫入便可:spa
>>> from io import StringIO >>> f = StringIO() >>> f.write('hello') 5 >>> f.write(' ') 1 >>> f.write('world!') 6 >>> print(f.getvalue()) hello world!
getvalue()
方法用於得到寫入後的str。.net
要讀取StringIO,能夠用一個str初始化StringIO,而後,像讀文件同樣讀取:code
>>> from io import StringIO >>> f = StringIO('Hello!\nHi!\nGoodbye!') >>> while True: ... s = f.readline() ... if s == '': ... break ... print(s.strip()) ... Hello! Hi! Goodbye!
StringIO操做的只能是str,若是要操做二進制數據,就須要使用BytesIO。orm
BytesIO實現了在內存中讀寫bytes,咱們建立一個BytesIO,而後寫入一些bytes:blog
>>> from io import BytesIO >>> f = BytesIO() >>> f.write('中文'.encode('utf-8')) 6 >>> print(f.getvalue()) b'\xe4\xb8\xad\xe6\x96\x87'
請注意,寫入的不是str,而是通過UTF-8編碼的bytes。接口
>>> from io import BytesIO >>> f = BytesIO() >>> f.write('中文') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: a bytes-like object is required, not 'str'
和StringIO相似,能夠用一個bytes初始化BytesIO,而後,像讀文件同樣讀取:ip
>>> from io import StringIO >>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87') >>> f.read() b'\xe4\xb8\xad\xe6\x96\x87'
StringIO和BytesIO是在內存中操做str和bytes的方法,使得和讀寫文件具備一致的接口。內存