Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert file into BytesIO object using python

Tags:

python

bytesio

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))
like image 941
user2961127 Avatar asked Dec 16 '19 22:12

user2961127


People also ask

Is BytesIO a file like object?

StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.

How do you define io in Python?

Python io module allows us to manage the file-related input and output operations. The advantage of using the IO module is that the classes and functions available allows us to extend the functionality to enable writing to the Unicode data.


1 Answers

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:

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.

like image 76
Stephan Klein Avatar answered Sep 17 '22 08:09

Stephan Klein