[Tutor] How to print the next line in python
Rich Lovely
roadierich at googlemail.com
Sat Sep 12 14:50:25 CEST 2009
2009/9/12 Dave Angel <davea at ieee.org>:
> 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'
>>
>>
>>
>
> Easiest way is probably to introduce another local, "previous_line"
> containing the immediately previous line each time through the loop. Then
> if "CL" is in the previous_line, you print current_line.
>
>
> (untested)
>
> infile=open('somefile.txt','r')
>
> previous_line = ""
>
> for current_line in infile:
> if 'CL' in previous_line:
> print current_line
>
> previous_line = current_line
> infile.close()
>
> Notice also that your call to readlines() was unnecessary. You can iterate
> through a text file directly with a for loop. That won't matter for a small
> file, but if the file is huge, this saves memory, plus it could save a pause
> a the beginning while the whole file is read by readlines(). I also added a
> close(), for obvious reasons.
>
> DaveA
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
If we want to be really modern:
#Only works on python 2.5 or later. On 2.6 (or higher...), the
following line is not needed.
from __future__ import with_statement
previous_line = ""
with open('somefile.txt','r') as infile:
for current_line in infile:
if 'CL' in previous_line:
print current_line
previous_line = current_line
--
Rich "Roadie Rich" Lovely
There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
More information about the Tutor
mailing list