Python 3 中字符串是str类型,内存读写字符串用StringIO。内存读写bytes 用BytesIO。bytes 和str 转换用encode 和decode
In [4]: s = "黄哥"
In [5]: type(s)
Out[5]: str
In [6]: b = s.encode('utf-8')
In [7]: b
Out[7]: b'\xe9\xbb\x84\xe5\x93\xa5'
In [8]: type(b)
Out[8]: bytes
In [9]: c = b.decode('utf-8')
In [10]: c
Out[10]: '黄哥'
In [11]:
classio.StringIO(initial_value='', newline='\n')
An in-memory stream for text I/O. The text buffer is discarded when the close() method is called.
The initial value of the buffer can be set by providing initial_value. If newline translation is enabled, newlines will be encoded as if by write(). The stream is positioned at the start of the buffer.
The newline argument works like that of TextIOWrapper. The default is to consider only\n characters as ends of lines and to do no newline translation. If newline is set to None, newlines are written as \n on all platforms, but universal newline decoding is still performed when reading.
StringIO provides this method in addition to those from TextIOBase and its parents:
classio.BytesIO([initial_bytes])
A stream implementation using an in-memory bytes buffer. It inherits BufferedIOBase. The buffer is discarded when the close() method is called.
The optional argument initial_bytes is a bytes-like object that contains initial data.
BytesIO provides or overrides these methods in addition to those from BufferedIOBaseand IOBase:getbuffer()16.2. io — Core tools for working with streams
Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:
>>>
>>> b = io.BytesIO(b"abcdef")
>>> view = b.getbuffer()
>>> view[2:4] = b"56"
>>> b.getvalue()
b'ab56ef'
Note
As long as the view exists, the BytesIO object cannot be resized or closed.
New in version 3.2.