[Tutor] How to print the next line in python
Dave Angel
davea at ieee.org
Sat Sep 12 11:45:03 CEST 2009
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
More information about the Tutor
mailing list