Stringio
Most of the time, data read and write is not necessarily a file, but also can read and write in memory .
Stringio, as the name implies, reads and writes STR in memory.
To write Str to Stringio, we need to create a stringio and then write it like a file:
>>> from io import Stringio >>> f = >>> f.write ( hello " ) 5>>> F.write ( ' ' ) 1>>> F.write ( Span style= "color: #800000;" > '
getvalue()method is used to obtain the post-write Str.
To read Stringio, you can initialize the Stringio with a STR and then read it like a read file:
from Import Stringio>>> f = Stringio ('hello!\nhi!\ngoodbye! ' ) while True : ... = F.readline () ... if "' :... Break ... Print (S.strip ()) ... Hello! Hi! goodbye!
Bytesio
Stringio operation can only be str, if you want to manipulate binary data , you need to use Bytesio.
Bytesio implements read-write bytes in memory, we create a bytesio and then write some bytes:
from Import Bytesio>>> f = Bytesio ()>>> f.write (' Chinese '. Encode ( ' Utf-8 ' )print(F.getvalue ()) b'\xe4\xb8\xad\xe6\x96\x87'
Note that the write is not str, but the UTF-8 encoded bytes.
Similar to Stringio, you can initialize the Bytesio with a bytes, and then read like a read file :
from Import Bytesio>>> f = bytesio (b'\xe4\xb8\xad\xe6\x96\x87')> >> f.read () b'\xe4\xb8\xad\xe6\x96\x87'
Summary
Stringio and Bytesio are methods of operating str and bytes in memory, allowing for a consistent interface to read and write files.
Python Learning Notes (24) Stringio and Bytesio