deleting texts between patterns
Fredrik Lundh
fredrik at pythonware.com
Fri May 12 04:29:39 EDT 2006
<micklee74 at hotmail.com> skrev i meddelandet news:1147420279.664699.181200 at i40g2000cwc.googlegroups.com...
> 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?
what's wrong with a simple
emit = True
for line in open("q.txt"):
if line == "xyz\n":
emit = True
if emit:
print line,
if line == "abc\n":
emit = False
loop ? (this is also easy to tweak for cases where you don't want to include
the patterns in the output).
to print to a file instead of stdout, just replace the print line with a f.write call.
</F>
More information about the Python-list
mailing list