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的方法,使得和读写文件具备一致的接口
相关文章
相关标签/搜索