deleting texts between patterns

Duncan Booth duncan.booth at invalid.invalid
Fri May 12 04:29:09 EDT 2006


 wrote:

> hi
> say i have a text file
> 
> line1
> line2
> line3
> line4
> line5
> line6
> abc
> line8 <---to be delete
> line9  <---to be delete
> line10  <---to be delete
> line11  <---to be delete
> line12  <---to be delete
> line13 <---to be delete
> xyz
> line15
> line16
> line17
> line18
> 
> I wish to delete lines that are in between 'abc' and 'xyz' and print
> the rest of the lines. Which is the best way to do it? Should i get
> everything into a list, get the index of abc and xyz, then pop the
> elements out? or any other better methods? 
> thanks
> 

Something like this (untested code):

def filtered(f, stop, restart):
   f = iter(f)
   for line in f:
       yield line
       if line==stop:
           break
   for line in f:
       if line==restart:
           yield line
           break
   for line in f:
       yield line

for line in filtered(open('thefile'), "abc\n", "xyz\n"):
    print line



More information about the Python-list mailing list