Append binary file to another binary file

17,214

Solution 1

You need to actually open the second file and read its contents:

with open("binary_file_1", "ab") as myfile, open("binary_file_2", "rb") as file2:
    myfile.write(file2.read())

Solution 2

From the python module shutil

import os
import shutil

WDIR=os.getcwd()
fext=open("outputFile.bin","wb")
for f in lstFiles:
    fo=open(os.path.join(WDIR,f),"rb")
    shutil.copyfileobj(fo, fext)
    fo.close()
fext.close()

First we open the the outputFile.bin binary file for writing and then I loop over the list of files in lstFiles using the shutil.copyfileobj(src,dest) where src and dest are file objects. To get the file object just open the file by calling open on the filename with the proper mode "rb" read binary. For each file object opened we must close it. The concatenated file must be closed as well. I hope it helps

Solution 3

for file in files:
    async with aiofiles.open(file, mode='rb') as f:
        contents = await f.read()
    if file == files[0]:
        write_mode = 'wb'  # overwrite file
    else:
        write_mode = 'ab'  # append to end of file

    async with aiofiles.open(output_file), write_mode) as f:
        await f.write(contents)
Share:
17,214
Python_newbie
Author by

Python_newbie

Updated on June 27, 2022

Comments

  • Python_newbie
    Python_newbie almost 2 years

    I want to append a previously-written binary file with a more recent binary file created. Essentially merging them. This is the sample code I am using:

    with open("binary_file_1", "ab") as myfile:
        myfile.write("binary_file_2")
    

    Except the error I get is "TypeError: must be string or buffer, not file"

    But that's exactly what I am wanting to do! Add one binary file to the end of an earlier created binary file.

    I did try adding "wb" to the "myfile.write("binary_file_2", "wb")but it didn't like that.