Search code examples
pythonbytesio

Convert file into BytesIO object using python


I have a file and want to convert it into BytesIO object so that it can be stored in database's varbinary column.

Please can anyone help me convert it using python.

Below is my code:

f = open(filepath, "rb")
print(f.read())

myBytesIO = io.BytesIO(f)
myBytesIO.seek(0)
print(type(myBytesIO))

Solution

  • 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.