TypeError: a bytes-like object is required, not _io.BytesIO

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

TypeError: a bytes-like object is required, not _io.BytesIO #

To solve the Python "TypeError: a bytes-like object is required, not _io.BytesIO", call the read() method on the _io.BytesIO object, e.g. b.read(). The read method reads the bytes from the object and returns them.

typeerror typeerror bytes like object is required not str

Here is an example of how the error occurs.

main.py
import io b = io.BytesIO(b"abcd") print(type(b)) # <class '_io.BytesIO'> with open('example.zip', 'wb') as f: # ⛔️ TypeError: a bytes-like object is required, not '_io.BytesIO' f.write(b)

We tried using an _io.BytesIO object where a bytes object is expected.

To solve the error, call the read() method on the _io.BytesIO object.

main.py
import io b = io.BytesIO(b"abcd") print(type(b)) # <class '_io.BytesIO'> with open('example.zip', 'wb') as f: # 👇️ change the stream position to the start b.seek(0) # 👇️ read the bytes from the object f.write(b.read())

We used the seek method to change the stream position to an offset of 0 (to the beginning).

This means that we will start reading the stream from the start.

The read method can be used to read the bytes from an object and return them.

The method takes an optional size argument if you want to specify up to how many bytes to return.

If the argument is not provided, all bytes until the end of the file are returned.

Calling the seek() method with a position of 0 is important because if you use the `read` method somewhere else in your code, you would change the offset.

Here is an example that demonstrates this - once we call the read() method, the stream is positioned at the end, so it doesn't return anything.

main.py
import io b = io.BytesIO(b"abcd") with open('example.zip', 'wb') as f: # 👇️ change the stream position to the start b.seek(0) print(b.read()) # 👉️ b'abcd' print(b.read()) # 👉️ b''

You can use the seek(0) method to reset the stream position.

main.py
import io b = io.BytesIO(b"abcd") with open('example.zip', 'wb') as f: # 👇️ change the stream position to the start b.seek(0) print(b.read()) # 👉️ b'abcd' # 👇️ change the stream position to the start b.seek(0) print(b.read()) # 👉️ b'abcd'
Use the search field on my Home Page to filter through my more than 1,000 articles.