🌐
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())
🌐
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
Discussions

python - Difference between `open` and `io.BytesIO` in binary streams - Stack Overflow
I'm learning about working with streams in Python and I noticed that the IO docs say the following: The easiest way to create a binary stream is with open() with 'b' in the mode string: ... What is the difference between f as defined by open and f as defined by BytesIO. More on stackoverflow.com
🌐 stackoverflow.com
Does BytesIO need to be closed.
From my understanding, probably not, but it can't hurt. The information below is based on this Google Groups chat from 2015, so it could be outdated. StringIO at the very least only use RAM, so at worst not closing them could cause a memory leak, but CPython takes care of it for you. Of course if you use PyPy or some other implementation, things are different. BytesIO is a bit different in that it uses file descriptors, which are in limited supply for each process, but I wouldn't expect you to need too many of these. Personally I'm something of a robustness enthusiast and prefer code that doesn't rely on implementation details over fast code, so I would recommend you to use context managers always, but this is subjective. More on reddit.com
🌐 r/learnpython
8
5
January 17, 2023
<class 'bytes'> vs <class '_io.BytesIO'>
These are completely different things. BytesIO is, as the name implies, an input/output object. It doesn't represent the bytes themselves, it represents a stream such as you might read from disk or receive over a network. bytes is the bytes themselves, ie the data that is received via a BytesIO. More on reddit.com
🌐 r/learnpython
4
1
December 1, 2022
Is there memory benefit using io.BytesIO/StringIO vs bytes/str
That "funny" _io module is the way that CPython implements modules in C. There are several more of them, e.g. _csv. Typically the Python module attempts to import the faster C code, but if it can't it reverts to a pure Python implementation. To answer your question, from class io.RawIOBase , second paragraph, "Raw binary I/O typically provides low-level access to an underlying OS device or API, and does not try to encapsulate it in high-level primitives (this is left to Buffered I/O and Text I/O, described later in this page).". This is the super class for io.BytesIO. I could not find similar wording for io.StringIO. More on reddit.com
🌐 r/Python
3
1
September 29, 2015
🌐
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.
🌐
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 new BytesIO object named binary_buffer is created to emulate an in-memory file for binary data. The hexadecimal representation of the string "Hello" is written to the buffer using write.
🌐
Python
wiki.python.org › moin › BytesIO
BytesIO - Python Wiki
April 28, 2011 - 6 7 >>> b = bytes() 8 >>> f = ... 254, 186, 190, 87, 65, 86, 69]) 13 """ 14 15 def __init__(self, buf, mode='r'): 16 """ Create a new BytesIO for reading or writing the given buffer....
🌐
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...
🌐
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.
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.)

Find elsewhere
🌐
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 …
🌐
Mellowd
mellowd.dev › python › using-io-bytesio
Using io.BytesIO() with Python - mellowd.dev
May 15, 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()
🌐
CodeRivers
coderivers.org › blog › io-bytesio-python
Python's `io.BytesIO`: A Comprehensive Guide - CodeRivers
February 22, 2026 - This blog post will delve into the fundamental concepts of io.BytesIO, its usage methods, common practices, and best practices. Whether you're a beginner or an experienced Python developer, understanding io.BytesIO can greatly enhance your data manipulation capabilities.
🌐
Learning Machine
gallon.me › using-the-bytesio-class-in-python
Using the BytesIO Class in Python - Learning Machine
February 14, 2025 - You can wrap the bytes in a BytesIO to provide that interface: import io from PIL import Image # Pillow library for image processing # Simulated image bytes (normally you'd get this from a request) image_bytes = b'...' # Replace with actual image bytes # Wrap the bytes in a BytesIO object image_stream = io.BytesIO(image_bytes) # Open the image using PIL, which expects a file-like object image = Image.open(image_stream) image.show() # Display the image
🌐
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.
🌐
Code-learner
code-learner.com › home › python stringio and bytesio example
Python StringIO And BytesIO Example ·
March 21, 2021 - <_io.BytesIO object at 0x7f8f3397de30> b'I love python' <_io.StringIO object at 0x7f8f33a847d0> hello python
🌐
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 - In Python 2.7 StringIO module was capable handling the Byte as well Unicode But in python3 you will have to use separate BytesIO for handling Byte strings and StringIO for handling Unicode strings. ... StringIO.StringIO allows either Unicode or Bytes string. cStringIO.StringIO requires a string that is encoded as a bytes string. ... >>> 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.'
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert python bytes to io.bytesio
5 Best Ways to Convert Python Bytes to io.BytesIO - Be on the Right Side of Change
February 23, 2024 - This code initializes an empty io.BytesIO object. The write() method is then used to write a byte string to the buffer. The write() method returns the number of bytes written. For dealing with hexadecimal string representations of byte data, Python provides a way to first convert the hex data to bytes and then wrap it into an io.BytesIO object.
🌐
Confessions of a Data Guy
confessionsofadataguy.com › home › you have to try this… from io import stringio, bytesio
You Have to Try This... from io import StringIO, BytesIO - Confessions of a Data Guy
January 2, 2021 - One minor detail to remember about a StringIO/BytesIO is that when created, it acts like an already opened file! Let’s look at some examples of how this could work. Simplistic, but to the point. from io import StringIO, BytesIO import csv in_memory_file = StringIO() csv_writer = csv.writer(in_memory_file) csv_writer.writerows([[1, 2, 3], [4, 5, 6]]) in_memory_file.seek(0) for row in in_memory_file: print(row)
🌐
W3Schools
w3schools.com › python › ref_module_io.asp
Python io Module
The io module provides Python's main facilities for dealing with streams (text, binary, buffered). Use it to work with files and in-memory streams via high-level classes like TextIOWrapper, BytesIO, and StringIO.
🌐
Andrew Wheeler
andrewpwheeler.com › 2022 › 11 › 02 › using-io-objects-in-python-to-read-data
Using IO objects in python to read data | Andrew Wheeler
November 2, 2022 - # Example 2, grabbing zipped contents import zipfile from io import BytesIO census_url = 'https://www2.census.gov/programs-surveys/acs/summary_file/2019/data/2019_5yr_Summary_FileTemplates.zip' req = requests.get(census_url) # Can use BytesIO for this content zf = zipfile.ZipFile(BytesIO(req.content))