Convert from '_io.BytesIO' to a bytes-like object in python3.6? Convert from '_io.BytesIO' to a bytes-like object in python3.6? python python

Convert from '_io.BytesIO' to a bytes-like object in python3.6?


It's a file-like object. Read them:

>>> b = io.BytesIO(b'hello')>>> b.read()b'hello'

If the data coming in from body is too large to read into memory, you'll want to refactor your code and use zlib.decompressobj instead of zlib.decompress.


In case you write into the object first, make sure to reset the stream before reading:

>>> b = io.BytesIO()>>> image = PIL.Image.open(path_to_image)>>> image.save(b, format='PNG')>>> b.seek(0)>>> b.read()b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x06\xcf\x00\x00\x03W\x08\x02\x00'

or directly get the data with getvalue

>>> b.getvalue()b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x06\xcf\x00\x00\x03W\x08\x02\x00'