Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a binary stream buffer into a file in Python 3 without explicitly read from it?

I have a file that I want to write bytes into from a binary stream buffer (either io.BufferedReader or io.BytesIO) without explicitly read() from it.

I cannot write its content to the file because file.write() only accepts bytes-like object.

Here's an example of what I want to achieve:

import io

read_buffer = io.BytesIO(b'buffer bytes content')

with open('target_file', 'wb') as file:
    file.write(read_buffer)
    # file.write(read_buffer.read()) is not a solution

I prefer to use either Python's built-in modules or external Python package to handle it.

like image 981
Eido95 Avatar asked Sep 12 '25 23:09

Eido95


1 Answers

It is possible to do using shutil.copyfileobj

import io
import shutil    

read_buffer = io.BytesIO(b'buffer content 1')

with open('target_file', 'wb') as file:
    shutil.copyfileobj(read_buffer, file)
like image 175
Eido95 Avatar answered Sep 14 '25 13:09

Eido95