Copying io.BytesIO content to a file in Python

Problem:

In Python, you have an io.BytesIO instance containing some data. You want to copy that data to a file (or another file-like object).

Solution

Use this function:

def copy_filelike_to_filelike(src, dst, bufsize=16384):
    while True:
        buf = src.read(bufsize)
        if not buf:
            break
        dst.write(buf)

Usage example:

import io

myBytesIO = io.BytesIO(b"test123")

with open("myfile.txt", "wb") as outfile:
    copy_filelike_to_filelike(myBytesIO, outfile)
# myfile.txt now contains "test123" (no trailing newline)