Python_newbie
Python_newbie

Reputation: 163

Append binary file to another binary file

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.

Upvotes: 11

Views: 24652

Answers (3)

Robert Ribas
Robert Ribas

Reputation: 317

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

Upvotes: 7

Max Gómez
Max Gómez

Reputation: 69

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)

Upvotes: 1

mhawke
mhawke

Reputation: 87084

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())

Upvotes: 22

Related Questions