[Tutor] How to print the next line in python

Eduardo Vieira eduardo.susan at gmail.com
Mon Sep 14 18:05:43 CEST 2009


On Sat, Sep 12, 2009 at 10:53 PM, Lie Ryan <lie.1296 at gmail.com> wrote:
> ranjan das wrote:
>>
>> Hi,
>>
>> I am new to python and i wrote this piece of code which is ofcourse not
>> serving my purpose:
>>
>> Aim of the code:
>>
>> To read a file and look for lines which contain the string 'CL'. When
>> found, print the entry of the next line (positioned directly below the
>> string 'CL') ....continue to do this till the end of the file (since there
>> are more than one occurrences of 'CL' in the file)
>>
>> My piece of code (which just prints lines which contain the string 'CL')
>>
>> f=open('somefile.txt','r')
>>
>> for line in f.readlines():
>>
>>     if 'CL' in line:
>>              print line
>>
>>
>> please suggest how do i print the entry right below the string 'CL'
>>
>>
>
> Will "the next line" ever contains "CL"? And if it does, should we print the
> next, next line. That is, in case of:
>
> abcCLdef
> ghiCLjkl
> mnopqrst
>
> should we print:
> ghiCLjkl
> mnopqrst
>
> or:
> ghiCLjkl
>
> if the latter is the case, then you can advance the file's cursor:
>
> with open('myfile.txt') as f:
>    for line in f:
>        if 'CL' in line:
>            print next(f)
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

I like this solution, but it brings a StopIteration error in case the
last line contains a 'CL'

Regards,
Eduardo


More information about the Tutor mailing list