python learning - StringIO and BytesIO

StringIO

In many cases, data read and write is not necessarily a file, but can also be read and written in memory.

StringIO, as the name suggests, reads and writes str in memory.

To write str to StringIO, we need to create a StringIO first, and then write it like a file:

>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!

getvalue()method is used to get the written str.

To read StringIO, initialize StringIO with a str, then read it like a file:

>>> 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 can only operate on str. If you want to operate binary data, you need to use BytesIO.

BytesIO implements reading and writing bytes in memory, we create a BytesIO, and then write some bytes:

>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b ' \ xe4 \ xb8 \ limit \ xe6 \ x96 \ x87 '

Note that not str, but UTF-8 encoded bytes are written.

>>> 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'

Similar to StringIO, BytesIO can be initialized with a bytes, and then read like a file:

>>> from io import StringIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b ' \ xe4 \ xb8 \ limit \ xe6 \ x96 \ x87 '

summary

StringIO and BytesIO are methods for manipulating str and bytes in memory, so that they have a consistent interface with reading and writing files.

Reprinted from https://blog.csdn.net/youzhouliu/article/details/51914536

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325061783&siteId=291194637