Search code examples
pythonpython-2.7appendbinaryfiles

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.


Solution

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