Text processing and file creation

Ricardo Aráoz ricaraoz at gmail.com
Thu Sep 6 13:22:21 EDT 2007


Shawn Milochik wrote:
> On 9/5/07, malibuster at gmail.com <malibuster 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?
>> In advance, thanks for your help.
>>

Maybe (untested):

def read5Lines(f):
    L = f.readline()
    while L :
        yield (L,f.readline(),f.readline(),f.readline(),f.readline())
        L = f.readline()

in = open('C:\YourFile','rb')
for fileNo, fiveLines in enumerate(read5Lines(in)) :
    out = open('c:\OutFile'+str(fileNo), 'wb')
    out.writelines(fiveLines)
    out.close()

or something similar? (notice that in the last output file you may have
a few (4 at most) blank lines)







More information about the Python-list mailing list