26

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))
user2961127
  • 963
  • 2
  • 17
  • 29

1 Answers1

58

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.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Stephan Klein
  • 1,177
  • 11
  • 20
  • Awesome, that made it clear. Thanks for the explanation. – user2961127 Dec 16 '19 at 22:51
  • I, for one, certainly hope the code I am passing the bytesIO to is _not_ "smart" enough to stream the file from disk, as I am trying to keep the harddrive busy loading and saving, rather than waiting for loaded files to be processed. – Elias Hasle May 21 '21 at 07:41