How to read bytes as stream in python 3

Question:

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:

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?

Asked By: José Luis

||

Answers:

You can use a 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'
Answered By: JBernardo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.