How to read bytes as a stream in python 3

I read the binary file (ogg vorbis) and extract several packages for further processing. These packages are python byte objects, and we will use them to read using the read (n_bytes) method. Now my code looks something like this:

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 to create a readable stream from a byte object?

+6
source share
1 answer

You can use io.BytesIO file-like object

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

All Articles