start reading from certain line

norseman norseman at
Wed Jul 9 18:59:32 CEST 2008

Tim Cook wrote:
> On Wed, 2008-07-09 at 03:30 -0700, antar2 wrote:
>> I am a starter in python and would like to write a program that reads
>> lines starting with a line that contains a certain word.
>> For example the program starts reading the program when a line is
>> encountered that contains 'item 1'
>> The weather is nice
>> Item 1
>> We will go to the seaside
>> ...
>> Only the lines coming after Item 1 should be read
> file=open(filename)
> while True:
>    line=file.readline()
>    if not line:
>       break
>       if 'Item 1' in line:
>          print line
> HTH,
> Tim
> ------------------------------------------------------------------------
> --

I would use:

readthem= 0
while readthem == 0:
   if not line:
   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

The first while has lots of needed tests causing lots of bouncing about.
May even need more tests to make sure it is right tag point. As in if 
'Item 1' accidentally occurred in a line previous to intended one.
The second while just buzzes on through.
If the objective is to process from tag point on then processing code 
will be cleaner, easier to read in second while.

in this form the line terminators in the file are also printed and then 
print attaches it's own EOL (newline). This gives a line double spacing 
effect, at least in Unix.  Putting the comma at the end (print line,) 
will stop that. You will need to modify two lines if used.  Which to use 
depends on you.

norseman at

More information about the Python-list mailing list