1

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...

Nico
  • 323
  • 4
  • 14

2 Answers2

2
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.

blakev
  • 4,154
  • 2
  • 32
  • 52
  • 1
    This will actually __replace__ the content of `original` with `other`. Opening an existing file a in write ("w") mode immediatly erases the file's content. To append to an existing file you want to open in append ("a") mode, obviously. – bruno desthuilliers Oct 11 '17 at 07:14
1

You can't merge file objects. You can make a list of each file and extended them

files_combined = list(open("example.bin", "wb")) + list(open("file_2"))

Will return a list with all the lines in file_2 appended to file_1, but in a new list. You can then save it to a new file, or overwrite one of the files.

Chen A.
  • 10,140
  • 3
  • 42
  • 61