append one file to another

John Machin sjmachin at lexicon.net
Tue Jul 12 19:57:28 EDT 2005


b83503104 at yahoo.com wrote:
> Hi,
> 
> I want to append one (huge) file to another (huge) file.  The current
> way I'm doing it is to do something like:
> 
> infile = open (infilename, 'r')
> filestr = infile.read()
> outfile = open(outfilename, 'a')
> outfile.write(filestr)
> 
> I wonder if there is a more efficient way doing this?

Don't wonder, like the ancient philosophers; be an empiricist :-)


> Thanks.
> 

If the files are truly huge, you run the risk of exhausting real memory 
and having to swap.

Try this:
Having opened the files,

for line in infile:
     outfile.write(line)

Otherwise look at the docs for read the method and check out the "size" 
argument.

General warnings: (1) If you want to be portable, consider text/binary 
differences. (2) Consider what to do if the last line in <outfilename> 
is not terminated.



More information about the Python-list mailing list