Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read bytes as stream in python 3

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?

like image 857
José Luis Avatar asked Feb 13 '13 17:02

José Luis


People also ask

What is byte stream in Python?

Byte streams are a sequence of bytes used by programs to input and output information.

How do you cast a byte in Python?

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.


1 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'
like image 113
JBernardo Avatar answered Oct 19 '22 01:10

JBernardo