How to merge two binary files into one?

Grant Edwards grante at visi.com
Mon Apr 4 22:54:41 EDT 2005


On 2005-04-05, could ildg <could.net at gmail.com> wrote:
>> > I want to merge file A and file B into a new file C, All of
>> > them are binary.
>> 
>> file('C','wb').write(file('A','rb').read()+file('B','rb').read())
>
> 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()

-- 
Grant Edwards                   grante             Yow!  I feel like a wet
                                  at               parking meter on Darvon!
                               visi.com            



More information about the Python-list mailing list