StringIO和BytesIO

一、StringIO
不少時候,數據讀寫不必定是文件,也能夠在內存中讀寫。
StringIO顧名思義就是在內存中讀寫str。
要把str寫入StringIO,咱們須要先建立一個StringIO,而後,像文件同樣寫入便可:
>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!
getvalue()方法用於得到寫入後的str。
要讀取StringIO,能夠用一個str初始化StringIO,而後,像讀文件同樣讀取:
>>> from io import StringIO
>>> f = StringIO('Hello!\nHi!\nGoodbye!')
>>> while True:
...     s = f.readline()
...     if s == '':
...         break
...     print(s.strip())
...
Hello!
Hi!
Goodbye!

  

 
 
二、BytesIO
StringIO操做的只能是str,若是要操做二進制數據,就須要使用BytesIO。
BytesIO實現了在內存中讀寫bytes,咱們建立一個BytesIO,而後寫入一些bytes:
>>> 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。
和StringIO相似,能夠用一個bytes初始化BytesIO,而後,像讀文件同樣讀取:
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'

 

 
小結:
  StringIO和BytesIO是在內存中操做str和bytes的方法,使得和讀寫文件具備一致的接口
相關文章
相關標籤/搜索