1.1 Stringio & BytesIO1.1.1 Stringio
Stringio , as the name implies, reads and writes STR in memory .
Write Stringio
>>> Fromio Import Stringio
>>> f = Stringio ()
>>> f.write (' Hello ')
5
>>> F.write (")
1
>>> f.write (' world! ')
6
>>> f.getvalue ()
' Hello world! '
>>> print (F.getvalue ())
Hello world!
Read Stringio
>>> from IO import Stringio
>>> f = Stringio (' Xiongxiong\nlove\ndaidai ')
>>> while True:
... s = f.readline () # is not the same as the readlines of the read file
... if s = = ":
... break
... print (S.strip ())
...
Xiongxiong
Love
Daidai
1.1.2 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 andthen write some bytes:
>>> from IO import Bytesio
>>> f = Bytesio ()
>>> f.write (' Chinese ' encode (' utf-8 '))
6
>>> print (F.getvalue ())
B ' \xe4\xb8\xad\xe6\x96\x87 '
Note that the write is not str, but the UTF-8 encoded bytes.
and the similar to Stringio, you can initialize the Bytesio with a bytes andthen read like a read file:
>>> from IO import Stringio
>>> F =bytesio (b ' \xe4\xb8\xad\xe6\x96\x87 ')
>>> F.read ()
B ' \xe4\xb8\xad\xe6\x96\x87 '
This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1826524
Python IO programming--stringio & Bytesio