Text processing and file creation

Arnaud Delobelle arnodel at googlemail.com
Wed Sep 5 23:31:23 CEST 2007


On Sep 5, 5:13 pm, "malibus... at gmail.com" <malibus... at gmail.com>
wrote:
> I have a text source file of about 20.000 lines.>From this file, I like to write the first 5 lines to a new file. Close
>
> that file, grab the next 5 lines write these to a new file... grabbing
> 5 lines and creating new files until processing of all 20.000 lines is
> done.
> Is there an efficient way to do this in Python?

Sure!

> In advance, thanks for your help.

from my_useful_functions import new_file, write_first_5_lines,
done_processing_file, grab_next_5_lines, another_new_file, write_these

in_f = open('myfile')
out_f = new_file()
write_first_5_lines(in_f, out_f) # write first 5 lines
close(out_f)
while not done_processing_file(in_f): # until done processing
   lines = grab_next_5_lines(in_f) # grab next 5 lines
   out_f = another_new_file()
   write_these(lines, out_f) # write these
   close(out_f)
print "all done!" # All done
print "Now there are 4000 files in this directory..."

Python 3.0 - ready (I've used open() instead of file())

HTH

--
Arnaud





More information about the Python-list mailing list