Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 381
Python_newbie Avatar asked Sep 18 '14 11:09

Python_newbie


3 Answers

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())
like image 123
mhawke Avatar answered Sep 22 '22 13:09

mhawke


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

like image 22
Robert Ribas Avatar answered Sep 19 '22 13:09

Robert Ribas


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)
like image 30
Max Gómez Avatar answered Sep 20 '22 13:09

Max Gómez