Appearance
StringIO and BytesIO
StringIO
Often, data reading and writing do not necessarily involve files; it can also be done in memory.
StringIO
, as the name suggests, is used for reading and writing strings (str
) in memory.
To write a string to StringIO
, we first need to create a StringIO
object, and then we can write to it like a file:
python
from io import StringIO
f = StringIO()
f.write('hello') # Returns the number of characters written (5)
f.write(' ') # Returns the number of characters written (1)
f.write('world!') # Returns the number of characters written (6)
print(f.getvalue()) # 'hello world!'
The getvalue()
method is used to obtain the string written to StringIO
.
To read from StringIO
, we can initialize it with a string and then read from it like reading from a file:
python
from io import StringIO
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
BytesIO
StringIO
can only handle strings. If you need to work with binary data, you should use BytesIO
.
BytesIO
allows reading and writing bytes in memory. We create a BytesIO
object and write some bytes to it:
python
from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8')) # Write UTF-8 encoded bytes
print(f.getvalue()) # Outputs: b'\xe4\xb8\xad\xe6\x96\x87'
Note that what is written is not a string, but rather the bytes encoded in UTF-8.
Similar to StringIO
, you can initialize BytesIO
with bytes and read from it like reading from a file:
python
from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
print(f.read()) # Outputs: b'\xe4\xb8\xad\xe6\x96\x87'
Summary
StringIO
and BytesIO
are methods for operating on strings (str
) and bytes in memory, respectively, providing a consistent interface similar to reading and writing files.