In many cases, reading and writing data does not necessarily involve files; it can also be done in memory.
As the name suggests, StringIO enables reading and writing of strings (str) in memory.
To write a string to StringIO, you first need to create a StringIO object, then write to it just like you would with a file:
>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!
The getvalue() method is used to retrieve the written string.
To read from a StringIO object, you can initialize it with a string, then read from 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!
StringIO only operates on strings (str). If you need to handle binary data, you must use BytesIO.
BytesIO implements reading and writing of bytes in memory. We create a BytesIO object and write some bytes to it:
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
Note that what is written is not a string (str), but bytes encoded with UTF-8.
Similar to StringIO, you can initialize a BytesIO object with bytes and read from it like a file:
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'
StringIO and BytesIO are methods for manipulating strings (str) and bytes in memory, providing a consistent interface with file reading/writing operations.
do_stringio.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from io import StringIO
# write to StringIO:
f = StringIO()
f.write("hello")
f.write(" ")
f.write("world!")
print(f.getvalue())
# read from StringIO:
f = StringIO("姘撮潰缁嗛鐢燂紝\n鑿辨瓕鎱㈡參澹般€俓n瀹涵涓村皬甯傦紝\n鐏伀澶滃鏄庛€�")
while True:
s = f.readline()
if s == "":
break
print(s.strip())do_bytesio.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from io import BytesIO
# write to BytesIO:
f = BytesIO()
f.write(b"hello")
f.write(b" ")
f.write(b"world!")
print(f.getvalue())
# read from BytesIO:
data = "浜洪棽妗傝姳钀斤紝澶滈潤鏄ュ北绌恒€傛湀鍑烘儕灞遍笩锛屾椂楦f槬娑т腑銆�".encode("utf-8")
f = BytesIO(data)
print(f.read())