Skip to content
Advertisement

Convert BytesIO into File

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?

Advertisement

Answer

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:

  • Based on the first paragraph in the io module’s documentation, it sounds like all the concrete classes- including BytesIO- are file-like objects. Without knowing what code you’ve tried so far, I don’t know if you have tried passing the BytesIO to the module you’re using.
  • On the off chance that doesn’t work, you can simply convert BytesIO to a another io Writer/Reader/Wrapper by passing it to the constructor. Example:

.

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 
  • You may need to check which kind of Reader/Writer/Wrapper is expected by the module you’re using to convert the BytesIO to the correct one
  • I believe I have heard that (for memory reasons, due to extremely large excel files) excel modules do not load the entire file. If this ends up meaning that what you need is a physical file on the disk, then you can easily write the Excel file temporarily and just delete it when you’re done. Example:

.

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement