These advertisements helps me to keep writing articles on this website

Copying a buffered stream in Python

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

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 August 10, 2020. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.