Reputation: 1562
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?
Upvotes: 99
Views: 161146
Reputation: 457
Python 3.10:
pathlib.Path('temp_file_name.tmp') \
.write_bytes(io.BytesIO(b'data') \
.getbuffer() \
.tobytes())
Upvotes: 4
Reputation: 4415
pathlib.Path('file').write_bytes(io.BytesIO(b'data').getbuffer())
Upvotes: 15
Reputation: 1525
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.
Upvotes: 49
Reputation: 136615
# Create an example
from io import BytesIO
bytesio_object = BytesIO(b"Hello World!")
# Write the stuff
with open("output.txt", "wb") as f:
f.write(bytesio_object.getbuffer())
Upvotes: 96