2

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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.