如何在python 3中以流的形式读取字节

时间:2022-01-17 20:10:26

I'm reading a binary file (ogg vorbis) and extracting some packets for later processing. These packets are python bytes objects, and would we useful read them with a "read(n_bytes)" method. Now my code is something like this:

我正在读取一个二进制文件(ogg vorbis)并提取一些包以备以后处理。这些包是python字节对象,我们可以使用“read(n_bytes)”方法读取它们。我的代码是这样的

packet = b'abcd'
some_value = packet[0:2]
other_value = packet[2:4]

And I want something like this:

我想要这样的东西:

packet = b'abcd'
some_value = packet.read(2)
other_value = packet.read(2)

How can I create a readable stream from a bytes object?

如何从字节对象创建可读流?

1 个解决方案

#1


11  

You can use a io.BytesIO file-like object

你可以用io。BytesIO类文件对象

>>> import io
>>> file = io.BytesIO(b'this is a byte string')
>>> file.read(2)
b'th'
>>> file.read(2)
b'is'

#1


11  

You can use a io.BytesIO file-like object

你可以用io。BytesIO类文件对象

>>> import io
>>> file = io.BytesIO(b'this is a byte string')
>>> file.read(2)
b'th'
>>> file.read(2)
b'is'