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 = stream_source.read(buffer_size)
if text == "": # read after EOF returns an empty string
print("EOF")
break
else:
print(f"read {len(text)} bytes ({text})")
stream_target.write(text)
print("target stream size", stream_target.tell())
stream_target.seek(0)
print("target stream contents", stream_target.read())
# todo: close streams or use with
Output:
read 4 bytes (0123)
read 4 bytes (4567)
read 2 bytes (89)
EOF
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.