How to merge two binary files into one?

C

could ildg

I want to merge file A and file B into a new file C,
All of them are binary.
How to do that?
thanks a lot.
 
G

Grant Edwards

Python is really magic, even merge file can use "+".

You probably shouldn't use the above code for very large files,
since it reads files A and B entirely into memory before
writing the combined data to C.

For large files, something like this is probably a better idea:

fout = file('C','wb')
for n in ['A','B']:
fin = file(n,'rb')
while True:
data = fin.read(65536)
if not data:
break
fout.write(data)
fin.close()
fout.close()
 
C

could ildg

Thank Grant, it works well.

Python is really magic, even merge file can use "+".

You probably shouldn't use the above code for very large files,
since it reads files A and B entirely into memory before
writing the combined data to C.

For large files, something like this is probably a better idea:

fout = file('C','wb')
for n in ['A','B']:
fin = file(n,'rb')
while True:
data = fin.read(65536)
if not data:
break
fout.write(data)
fin.close()
fout.close()
 
A

Andrew Dalke

Grant said:
For large files, something like this is probably a better idea:

Or with the little-used shutil module, and keeping your
nomenclature and block size of 65536

import shutil
fout = file('C', 'wb')
for n in ['A', 'B']:
fin = file(n, 'rb')
shutil.copyfileobj(fin, fout, 65536)
fin.close()
fout.close()


Andrew
(e-mail address removed)
 
C

could ildg

I'm so glad that this this problem has so many recipes.

Grant said:
For large files, something like this is probably a better idea:

Or with the little-used shutil module, and keeping your
nomenclature and block size of 65536

import shutil
fout = file('C', 'wb')
for n in ['A', 'B']:
fin = file(n, 'rb')
shutil.copyfileobj(fin, fout, 65536)
fin.close()
fout.close()

Andrew
(e-mail address removed)
 
G

Grant Edwards

Or with the little-used shutil module, and keeping your
nomenclature and block size of 65536

I knew I should have looked through shutil to see if there was
already something like that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top