132

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:

f = open("myfile.jpg", "rb")

In-memory binary streams are also available as BytesIO objects:

f = io.BytesIO(b"some initial binary data: \x00\x01")

What is the difference between f as defined by open and f as defined by BytesIO. In other words, what makes a "In-memory binary stream" and how is that different from what open does?

Community
  • 1
  • 1
Luke Whyte
  • 1,407
  • 2
  • 11
  • 10

2 Answers2

183

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

vallentin
  • 23,478
  • 6
  • 59
  • 81
  • 7
    Great answer; Question mentions `in memory stream` and you've referred to `in memory buffer`. Is there a difference in Python? It would be worth addressing briefly. From an English semantic perspective, `stream` implies a continuous flow of bits from source to sink (pushing from source), where buffer implies a cache of bits in the source ready for rapid fetching of chunks or pieces from the source (the sink pulling from the source). – Davos Apr 13 '18 at 13:10
  • I ran the small benchmark on my machine and got similar result using Python3.5, however, when I use Python 2.7, the "Concat" and "BytesIO" takes similar time, "Concat" is even slightly better. Anything wrong? this makes me confused. – JenkinsY Jul 13 '18 at 06:39
  • @Vallentin, sorry, you are wrong when you said "open("myfile.jpg", "rb") simply loads and returns the contents of myfile.jpg", see rhis `import io f = open("myfile.jpg", "rb") >>> isinstance(f, io.BufferedIOBase) True ` – Yahya Yahyaoui Mar 20 '19 at 22:24
  • Great answer, glad you even covered how to write the buffer back out to a file as needed! – Elias Yishak Apr 04 '22 at 14:34
32

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.)

Blckknght
  • 100,903
  • 11
  • 120
  • 169