Reputation: 3933
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?
Upvotes: 51
Views: 53408
Reputation: 33407
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'
Upvotes: 72