Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on Python IO

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

StringIO

In [1]:
from io import StringIO
In [2]:
sio = StringIO("")
sio
Out[2]:
<_io.StringIO at 0x7ff1ec50e940>
In [3]:
sio.write("hello world")
Out[3]:
11
In [4]:
sio.getvalue()
Out[4]:
'hello world'

BytesIO

  1. You can write anything into a BytesIO. For example, you can pass a BytesIO to pandas.DataFrame.to_parquet to write a pandas DataFrame to the BytesIO in the Parquet format. For more details, please refer to Pandas IO.
In [5]:
from io import BytesIO
In [6]:
bio = BytesIO()
bio
Out[6]:
<_io.BytesIO at 0x7ff1ec5340e0>
In [7]:
bio.write(b"hello world")
bio
Out[7]:
<_io.BytesIO at 0x7ff1ec5340e0>
In [8]:
bio.getvalue()
Out[8]:
b'hello world'
In [ ]:
 

Comments