Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert bytes into BufferedReader in python [duplicate]

I have a bytearray and want to convert into a buffered reader. A way of doing it is to write the bytes into a file and read them again.

sample_bytes = bytes('this is a sample bytearray','utf-8')
with open(path,'wb') as f:
    f.write(sample_bytes)
with open(path,'rb') as f:
    extracted_bytes = f.read()
print(type(f))

output:

<class '_io.BufferedReader'>

But I want these file-like features without having to save bytes into a file. In other words I want to wrap these bytes into a buffered reader so I can apply read() method on it without having to save to local disk. I tried the code below

from io import BufferedReader
sample_bytes=bytes('this is a sample bytearray','utf-8')
file_like = BufferedReader(sample_bytes)
print(file_like.read())

but I'm getting an attribute error

AttributeError: 'bytes' object has no attribute 'readable'

How to I write and read bytes into a file like object, without saving it into local disc ?

like image 653
Uchiha Madara Avatar asked Nov 09 '17 10:11

Uchiha Madara


People also ask

Is the process of converting byte stream to original structure in Python?

Similarly, Decoding is process to convert a Byte object to String. It is implemented using decode() . A byte string can be decoded back into a character string, if you know which encoding was used to encode it. Encoding and Decoding are inverse processes.

What does bytes () do in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.


1 Answers

If all you are looking for is an in-memory file-like object, I would be looking at

from io import BytesIO
file_like = BytesIO(b'this is a sample bytearray')
print(file_like.read())
like image 163
EdJoJob Avatar answered Sep 21 '22 22:09

EdJoJob