How can you copy a stream to another stream when using a buffer?

Copying a buffered stream in Python.

This example shows two string buffers. By using the methods read and write, the stream is copied between stream_source and stream_target.

The example uses the size parameter to read a buffer of 4 bytes each time.

import io

buffer_size = 4
stream_source = io.StringIO("0123456789")
stream_target = io.StringIO()

while True:
text =
if text == "":  # read after EOF returns an empty string
print(f"read {len(text)} bytes ({text})")

print("target stream size", stream_target.tell())
print("target stream contents",

# todo: close streams or use with


read 4 bytes (0123)
read 4 bytes (4567)
read 2 bytes (89)
target stream size 10
target stream contents 0123456789
Written by Loek van den Ouweland on 2020-08-10.
Questions regarding this artice? You can send them to the address below.