🌐
DigitalOcean
digitalocean.com › community › tutorials › python-io-bytesio-stringio
Python io.BytesIO and io.StringIO: Memory File Guide | DigitalOcean
August 3, 2022 - Just like what we do with variables, data can be kept as bytes in an in-memory buffer when we use the io module’s Byte IO operations. Here is a sample program to demonstrate this: import io stream_str = io.BytesIO(b"JournalDev Python: \x00\x01") print(stream_str.getvalue())
🌐
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 - BytesIO is like a virtual file that exists in the computer's memory, just like `StringIO`. However, it's tailored to handle binary data (bytes) instead of text. It lets you perform operations on these bytes, such as reading and writing, as if ...
🌐
ProgramCreek
programcreek.com › python › example › 1734 › io.BytesIO
Python Examples of io.BytesIO
def _deserialize(self, data, type_): if self.compress: # decompress the data if needed data = lz4.frame.decompress(data) if type_ == _NUMPY: # deserialize numpy arrays buf = io.BytesIO(data) data = np.load(buf) elif type_ == _PICKLE: # deserialize other python objects data = pickle.loads(data) else: # Otherwise we just return data as it is (bytes) pass return data
🌐
pythontutorials
pythontutorials.net › blog › how-the-write-read-and-getvalue-methods-of-python-io-bytesio-work
Python io.BytesIO Methods Explained: How write(), read(), and getvalue() Work – Key Differences & Usage Guide
io.BytesIO is a class in Python’s io module that creates an in-memory binary stream. It behaves like a file object but stores data in RAM rather than on disk, offering fast read/write operations with minimal overhead.
🌐
Centron
centron.de › startseite › python io – bytesio and stringio
Python io - BytesIO and StringIO
February 7, 2025 - In this lesson, we studied simple operations of python IO module and how we can manage the Unicode characters with BytesIO as well.
🌐
Plain English
python.plainenglish.io › how-to-use-io-stringio-and-io-bytesio-in-python-c7e10c3180b8
How to use io.StringIO and io.BytesIO in Python | by Lynn G. Kwong | Python in Plain English
November 1, 2024 - How to use io.StringIO and io.BytesIO in Python Learn an easy way to deal with file-like objects in memory The StringIO and BytesIO classes of the io module are in-memory file-like objects in Python …
🌐
AskPython
askpython.com › home › python io module: the complete practical reference
Python IO Module: The Complete Practical Reference - AskPython
February 16, 2023 - In this article, we learned about using the Python IO module, and it’s two main classes – io.BytesIO and io.StringIO for reading and writing byte and string data onto a buffer.
🌐
Code-learner
code-learner.com › home › python stringio and bytesio example
Python StringIO And BytesIO Example ·
March 21, 2021 - BytesIO implements read and write bytes data in memory. We create a BytesIO object and then write some bytes data into it.
🌐
Pixelsham
pixelsham.com › 2025 › 08 › 01 › introduction-to-bytesio
Introduction to BytesIO – pIXELsHAM
August 1, 2025 - from io import BytesIO # 1. Writing to an in-memory buffer buffer = BytesIO() buffer.write(b'Example binary data') all_data = buffer.getvalue() print(all_data) # 2. Reading from a buffer initialized with bytes buffer = BytesIO(b'Initial bytes here') print(buffer.read()) # 3. Using BytesIO in a context manager with BytesIO() as buf: buf.write(b'Context-managed buffer') buf.seek(0) print(buf.read()) ... 3Dprinting A.I. animation blender breaking news colour commercials composition cool design Featured hardware IOS jokes lighting modeling music nuke photogrammetry photography production python quotes reference software trailers ves VR
Find elsewhere
🌐
Mellowd
mellowd.dev › posts › using-io-bytesio
Using io.BytesIO() with Python | mellowd.dev
May 16, 2019 - #!/usr/bin/env python3 import io import matplotlib import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) fig, ax = plt.subplots() ax.plot(t, s) ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') ax.grid() b = io.BytesIO() plt.savefig(b, format='png') plt.close()
Top answer
1 of 2
208

For simplicity's sake, let's consider writing instead of reading for now.

So when you use open() like say:

with open("test.dat", "wb") as f:
    f.write(b"Hello World")
    f.write(b"Hello World")
    f.write(b"Hello World")

After executing that a file called test.dat will be created, containing 3x Hello World. The data wont be kept in memory after it's written to the file (unless being kept by a name).

Now when you consider io.BytesIO() instead:

with io.BytesIO() as f:
    f.write(b"Hello World")
    f.write(b"Hello World")
    f.write(b"Hello World")

Which instead of writing the contents to a file, it's written to an in memory buffer. In other words a chunk of RAM. Essentially writing the following would be the equivalent:

buffer = b""
buffer += b"Hello World"
buffer += b"Hello World"
buffer += b"Hello World"

In relation to the example with the with statement, then at the end there would also be a del buffer.

The key difference here is optimization and performance. io.BytesIO is able to do some optimizations that makes it faster than simply concatenating all the b"Hello World" one by one.

Just to prove it here's a small benchmark:

  • Concat: 1.3529 seconds
  • BytesIO: 0.0090 seconds

import io
import time

begin = time.time()
buffer = b""
for i in range(0, 50000):
    buffer += b"Hello World"
end = time.time()
seconds = end - begin
print("Concat:", seconds)

begin = time.time()
buffer = io.BytesIO()
for i in range(0, 50000):
    buffer.write(b"Hello World")
end = time.time()
seconds = end - begin
print("BytesIO:", seconds)

Besides the performance gain, using BytesIO instead of concatenating has the advantage that BytesIO can be used in place of a file object. So say you have a function that expects a file object to write to. Then you can give it that in-memory buffer instead of a file.

The difference is that open("myfile.jpg", "rb") simply loads and returns the contents of myfile.jpg; whereas, BytesIO again is just a buffer containing some data.

Since BytesIO is just a buffer - if you wanted to write the contents to a file later - you'd have to do:

buffer = io.BytesIO()
# ...
with open("test.dat", "wb") as f:
    f.write(buffer.getvalue())

Also, you didn't mention a version; I'm using Python 3. Related to the examples: I'm using the with statement instead of calling f.close()

2 of 2
42

Using open opens a file on your hard drive. Depending on what mode you use, you can read or write (or both) from the disk.

A BytesIO object isn't associated with any real file on the disk. It's just a chunk of memory that behaves like a file does. It has the same API as a file object returned from open (with mode r+b, allowing reading and writing of binary data).

BytesIO (and it's close sibling StringIO which is always in text mode) can be useful when you need to pass data to or from an API that expect to be given a file object, but where you'd prefer to pass the data directly. You can load your input data you have into the BytesIO before giving it to the library. After it returns, you can get any data the library wrote to the file from the BytesIO using the getvalue() method. (Usually you'd only need to do one of those, of course.)

🌐
Python
docs.python.org › 3 › library › io.html
io — Core tools for working with streams
Source code: Lib/io.py Overview: The io module provides Python’s main facilities for dealing with various types of I/O. There are three main types of I/O: text I/O, binary I/O and raw I/O. These ar...
🌐
Python Mania
pythonmania.org › home › blog › python io bytesio: a comprehensive guide
Python IO BytesIO: A Comprehensive Guide - Python Mania
May 16, 2023 - Let’s explore the different aspects of working with BytesIO. To create a Python IO BytesIO object, we simply instantiate it without any arguments.
🌐
Learning Machine
gallon.me › using-the-bytesio-class-in-python
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...
🌐
Pynerds
pynerds.com › io-bytesio-in-python
io.BytesIO in Python
Disclaimer: References to any specific company, product or services on this Site are not controlled by GoDaddy.com LLC and do not constitute or imply its association with or endorsement of third party advertisers
🌐
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 - Using buffer modules(StringIO, BytesIO, cStringIO) we can impersonate string or bytes data like a file.These buffer modules help us to mimic our data like a normal file which we can further use for processing.
🌐
Finxter
blog.finxter.com › home › learn python blog › converting python bytes to bytesio objects
Converting Python Bytes to BytesIO Objects - Be on the Right Side of Change
February 23, 2024 - This example demonstrates writing multiple bytes chunks to a BytesIO object sequentially. This is useful for processing data that comes in parts or streaming large amounts of data. For quick one-off tasks, Python’s generator expressions can be used to combine several byte strings and convert them to a BytesIO object in a single line of code.