I have a BytesIO
object containing the data of an excel document. The library I want to use doesn't support BytesIO
and expects a File object instead. How can I take my BytesIO
object and convert it into a File object?
First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.
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.
It takes input POSIX based arguments and returns a file descriptor which represents the opened file. It does not return a file object; the returned value will not have read() or write() functions.
It would be helpful if you supplied the library you were using to work on excel files, but here's a buckshot of solutions, based on some assumptions I'm making:
.
import io b = io.BytesIO(b"Hello World") ## Some random BytesIO Object print(type(b)) ## For sanity's sake with open("test.xlsx") as f: ## Excel File print(type(f)) ## Open file is TextIOWrapper bw=io.TextIOWrapper(b) ## Conversion to TextIOWrapper print(type(bw)) ## Just to confirm
.
import io import os with open("test.xlsx",'rb') as f: g=io.BytesIO(f.read()) ## Getting an Excel File represented as a BytesIO Object temporarylocation="testout.xlsx" with open(temporarylocation,'wb') as out: ## Open temporary file as bytes out.write(g.read()) ## Read bytes into file ## Do stuff with module/file os.remove(temporarylocation) ## Delete file when done
I'll hope that one of these points will solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With