Convert file into BytesIO object using python

Opening a file with open and mode read-binary already gives you a Binary I/O object.

Documentation:

The easiest way to create a binary stream is with open() with ‘b’ in the mode string:

f = open("myfile.jpg", "rb")

So in normal circumstances, you’d be fine just passing the file handle wherever you need to supply it. If you really want/need to get a BytesIO instance, just pass the bytes you’ve read from the file when creating your BytesIO instance like so:

from io import BytesIO

with open(filepath, "rb") as fh:
    buf = BytesIO(fh.read())

This has the disadvantage of loading the entire file into memory, which might be avoidable if the code you’re passing the instance to is smart enough to stream the file without keeping it in memory. Note that the example uses open as a context manager that will reliably close the file, even in case of errors.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)