start reading from certain line
norseman
norseman at hughes.net
Wed Jul 9 12:59:32 EDT 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
>
>
>
>
> ------------------------------------------------------------------------
>
> --
> http://mail.python.org/mailman/listinfo/python-list
=======================================================
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
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.
note-1:
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.
Steve
norseman at hughes.net
More information about the Python-list
mailing list