python中bytes用法_Python中BytesIO的使用场景,什么时间应该使用BytesIO?

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值