# 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())
Answer from Martin Thoma on Stack Overflow
🌐
Python
docs.python.org › 3 › library › io.html
io — Core tools for working with streams
Its subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer raw binary streams that are writable, readable, and both readable and writable, respectively. BufferedRandom provides a buffered interface to seekable streams. Another BufferedIOBase subclass, BytesIO, is a stream of in-memory bytes.
🌐
Medium
medium.com › @abhishekshaw020 › understanding-bytesio-handling-in-memory-files-like-a-pro-e1b767339468
Understanding BytesIO: Handling In-Memory Files Like a Pro | by Abhishek Shaw | Medium
March 31, 2025 - Think of BytesIO as a virtual file that lives in your computer’s memory (RAM) instead of your hard drive. It lets you read and write data just like a normal file, but everything stays in memory—fast, efficient, and no cleanup required!
Top answer
1 of 4
99
# 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())
2 of 4
49

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.

🌐
TechOverflow
techoverflow.net › 2019 › 07 › 24 › how-to-write-bytesio-content-to-file-in-python
How to write BytesIO content to file in Python | TechOverflow
July 23, 2019 - #!/usr/bin/env python3 from io import BytesIO import shutil # Initialie our BytesIO myio = BytesIO() myio.write(b"Test 123") def write_bytesio_to_file(filename, bytesio): """ Write the contents of the given BytesIO to a file.
🌐
GeeksforGeeks
geeksforgeeks.org › python › stringio-and-bytesio-for-managing-data-as-file-object
Stringio And Bytesio For Managing Data As File Object - GeeksforGeeks
July 24, 2025 - In this example, a BytesIO object named binary_buffer is initialized with the initial binary content "Hii GeeksforGeeks!". The read() method is used to retrieve the content from the buffer, and it's printed as "Read content." Subsequently, additional binary content, " I am adding New articles," is written to the buffer using the write method.
🌐
Medium
medium.com › @sarthakshah1920 › harnessing-the-power-of-in-memory-buffers-with-bytesio-0ac6d5493178
Harnessing the Power of In-Memory Buffers with BytesIO | by Sarthak Shah | Medium
December 24, 2023 - file_content = "This is a sample text file content." file_buffer = BytesIO() We write the file content to the in-memory buffer using the write method. In this case, we encode the text content to bytes using the encode() method before writing ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-io-bytesio-stringio
Python io.BytesIO and io.StringIO: Memory File Guide | DigitalOcean
August 3, 2022 - It does not return a file object; the returned value will not have read() or write() functions. Overall, io.open() function is just a wrapper over os.open() function. The os.open() function just also sets default config like flags and mode too while io.open() doesn’t to it and depends on ...
🌐
Python Assets
pythonassets.com › posts › what-is-io-bytesio-useful-for
What Is `io.BytesIO` Useful For? | Python Assets
July 19, 2024 - io.BytesIO is a standard class ... only in our program's memory. This means you can read from and write to it just like a file, but without creating any actual files on disk....
🌐
Webkul
webkul.com › home › python: using stringio and bytesio for managing data as file object
Python: Using StringIO and BytesIO for managing data as file object - Webkul Blog
October 1, 2019 - io.BytesIO requires a bytes string. StringIO.StringIO allows either Unicode or Bytes string. cStringIO.StringIO requires a string that is encoded as a bytes string. Here is a simple example using io module · >>> import io >>> string_out = io.StringIO() >>> string_out.write('A sample string which we have to send to server as string data.') 63##Length of data >>> string_out.getvalue() 'A sample string which we have to send to server as string data.'
Find elsewhere
🌐
Learning Machine
gallon.me › using-the-bytesio-class-in-python.html
Using the BytesIO Class in Python - Learning Machine
February 14, 2025 - The io.BytesIO class in Python is an in-memory stream for binary data. It provides a file-like interface that lets you read and write bytes just like you would with a file, but all the data is kept in memory rather than on disk.
🌐
Mellowd
mellowd.dev › python › using-io-bytesio
Using io.BytesIO() with Python - mellowd.dev
May 15, 2019 - #!/usr/bin/env python3 import io ... b = io.BytesIO() plt.savefig(b, format='png') plt.close() b is now an in-memory object that can be used wherever a file is used. Attach it to your tweet and you’re set. If you do need to now dump this image to storage you can still do that. with open("image.png", "wb") as f: f.write(b.re...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-write-bytes-to-file
Python - Write Bytes to File - GeeksforGeeks
May 17, 2025 - Explanation: This code uses BytesIO to create an in-memory binary stream (write_byte) containing the bytes (b"\xc3\x80"). It then writes the content of the in-memory stream to a file (test.bin) in binary write mode (wb).
🌐
Python⇒Speed
pythonspeed.com › articles › bytesio-reduce-memory-usage
The surprising way to save memory with BytesIO
February 27, 2025 - How does this work? BytesIO is using copy-on-write. Internally, it keeps a reference to the new bytes object returned from getvalue(). So long as you don’t write to the BytesIO, any reads can happen off the same memory.
🌐
ProgramCreek
programcreek.com › python › example › 1734 › io.BytesIO
Python Examples of io.BytesIO
:rtype : ``str`` ''' writer = avro.io.DatumWriter(avro.schema.parse(AVSC)) rawbytes = io.BytesIO() try: writer.write({ list.__name__: value }, avro.io.BinaryEncoder(rawbytes)) return rawbytes except avro.io.AvroTypeException: logging.getLogger('SPOT.INGEST.COMMON.SERIALIZER')\ .error('The type of ``{0}`` is not supported by the Avro schema.'
🌐
Medium
medium.com › @sunilnepali844 › simplifying-file-exports-in-python-with-io-bytesio-and-pandas-eb073d744064
Simplifying File Exports in Django with io.BytesIO and Pandas | by Sunil Nepali | Medium
July 11, 2024 - import io from rest_framework.response import Response import pandas as pd def export_to_excel(self, request): queryset = self.filter_queryset(self.get_queryset().order_by('id')) data = list(queryset.values()) df = pd.DataFrame(data) if not df.empty: if 'created_at' in df.columns: df['created_at'] = df['created_at'].dt.tz_localize(None) df['Date'] = pd.to_datetime(df['created_at']) df.pop('created_at') df.pop('updated_at') # df.fillna('', inplace=True) excel_buffer = io.BytesIO() writer = pd.ExcelWriter(excel_buffer, engine='xlsxwriter') df.to_excel(writer, index=False) writer.close() excel_buffer.seek(0) response = HttpResponse( excel_buffer.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response['Content-Disposition'] = 'attachment; filename="file_name.xlsx"' return response else: return HttpResponse("DataFrame is empty", status=204)