12

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.

1

3 Answers 3

24

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())
Sign up to request clarification or add additional context in comments.

1 Comment

This is great, the first file doesn't need to exist before hand either, so you can start from nothing.
8

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

2 Comments

This should be the accepted answer, as the one currently accepted tries to read all the data before writing it (which will cause problems for big files)
A context-manager variant of this answer would be a great answer.
1
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)

1 Comment

Add some description to your code. The logic would be more helpful than mere piece of code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.