python学习——StringIO和BytesIO

StringIO

不少时候,数据读写不必定是文件,也能够在内存中读写。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!

BytesIO

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的方法,使得和读写文件具备一致的接口。内存

转自https://blog.csdn.net/youzhouliu/article/details/51914536

相关文章
相关标签/搜索