start reading from certain line

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Jul 10 03:35:00 EDT 2008


On Wed, 09 Jul 2008 09:59:32 -0700, norseman wrote:

> I would use:
> 
> readthem= 0
> file=open(filename,'r')
> while readthem == 0:
>    line=file.readline()
>    if not line:
>      break
>    if 'Item 1' in line:
>      readthem= 1
>      # print line              # uncomment if 'Item 1' is to be printed
> while line:
>    line= file.readline()
>    print line                  # see note-1 below
> #      end of segment


Ouch! That's a convoluted way of doing something which is actually very 
simple. This is all you need:

outfile = open('filename', 'r')
for line in outfile:
    if 'item 1' in line.lower():
        print line
        break
for line in outfile:
    print line


If you don't like having two loops:

outfile = open('filename', 'r')
skip = True
for line in outfile:
    if 'item 1' in line.lower():
        skip = False
    if not skip:
        print line


And if you want an even shorter version:

import itertools
outfile = open('filename', 'r')
for line in itertools.dropwhile(
    lambda l: 'item 1' not in l.lower(), outfile):
    print line



-- 
Steven



More information about the Python-list mailing list