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?
Byte streams are a sequence of bytes used by programs to input and output information.
We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With