getting the line just before or after a pattern searched

Daniel Marcel Eichler shirow at gmx.net
Fri Feb 17 07:48:14 EST 2006


s99999999s2003 at yahoo.com wrote:

>i have a file something like this
>
>abcdefgh
>ijklmnopq
>12345678
>rstuvwxyz
>.....
>.....
>.....
>12345678
>.....
>
>whenever i search the file and reach 12345678, how do i get the line
>just above and below ( or more than 1 line above/below) the pattern
>12345678 and save to variables? thanks

source = file(bla).read().split('\n')
for i, line in enumerate(source):
	if line == '12345678':
		print '\n'.join( source[i-1:i+1] )

Something like this, for example. Of course, you must also secure that i-1 
isn't smaller than zero.


mfg

Daniel



More information about the Python-list mailing list