Reputation: 119
I am using an API that only takes file objects (a BufferedRandom object returned by open(file_name, 'r+b')
).
However, what I have in hand is a variable (bytes object, returned by with open(file_name, "rb") as file:
file.read()
)
I am wondering how to convert this bytes object into the BufferedRandom object to serve as input of the API, because if I input the bytes object as input to the API function, I got the error "bytes" object has no attribute "read".
Thank you very much!
Upvotes: 2
Views: 2619
Reputation: 41
Found an answer here.
You can get your bytes data into a file object with this:
import io
f = io.BytesIO(raw_bytes_data)
Now f
behaves just like a file object with methods like read
, seek
etc.
I had a similar issue when I needed to download (export) files from one REDCap database and upload (import) them into another using PyCap. The export_file
method returns the file contents as a raw bytestream, while import_file
needs a file object. Works with Python 3.
Upvotes: 3