Search code examples
pythonfilecopy-pasteextends

Paste file in new file in python


Is there a way to just open/create filehandle = open( "example.bin", "wb") and extend this file with an existing file?

I think about something like the .extend from function for lists Like so:

filehandle = open( "example.bin", "wb")
filehande.extend(existing_file.bin)

I know that i can read the existing file and write that to a variable/list and "paste" it in the new file but im curious if there is an easier option like this...


Solution

  • with open('original', 'a') as out_file, open('other', 'r') as ins_file:
        out_file.write(ins_file.read())
    

    This will append the contents of other onto original. If you're dealing with binary data you can change the mode on each to ab and rb.

    If the contents of the file are large you can do it in chunks too.