How to write BytesIO content to file in Python
In order to write the contents of a BytesIO
instance to a file, use this snippet:
with open("out.txt", "wb") as outfile:
# Copy the BytesIO stream to the output file
outfile.write(myio.getbuffer())
Note that getbuffer()
will not create a copy of the values in the BytesIO buffer and will hence not consume large amounts of memory.
You can also use this function:
def write_bytesio_to_file(filename, bytesio):
"""
Write the contents of the given BytesIO to a file.
Creates the file or overwrites the file if it does
not exist yet.
"""
with open(filename, "wb") as outfile:
# Copy the BytesIO stream to the output file
outfile.write(bytesio.getbuffer())
Full example:
#!/usr/bin/env python3
from io import BytesIO
import shutil
# Initialie our BytesIO
myio = BytesIO()
myio.write(b"Test 123")
def write_bytesio_to_file(filename, bytesio):
"""
Write the contents of the given BytesIO to a file.
Creates the file or overwrites the file if it does
not exist yet.
"""
with open(filename, "wb") as outfile:
# Copy the BytesIO stream to the output file
outfile.write(bytesio.getbuffer())
write_bytesio_to_file("out.txt", myio)