Break large file down into multiple files

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Feb 13 02:02:52 EST 2009


En Fri, 13 Feb 2009 04:44:54 -0200, brianrpsgt1 <brianlong at cox.net>  
escribió:

> New to python.... I have a large file that I need to break up into
> multiple smaller files. I need to break the large file into sections
> where there are 65535 lines and then write those sections to seperate
> files.  I am familiar with opening and writing files, however, I am
> struggling with creating the sections and writing the different
> sections to their own files.

This function copies at most n lines from fin to fout:

def copylines(fin, fout, n):
   for i, line in enumerate(fin):
     fout.write(line)
     if i+1>=n: break

Now you have to open the source file, create new files as needed and  
repeatedly call the above function until the end of source file. You'll  
have to enhace it bit, to know whether there are remaining lines or not.

-- 
Gabriel Genellina




More information about the Python-list mailing list