getting the line just before or after a pattern searched
Magnus Lycka
lycka at carmen.se
Wed Feb 22 11:18:56 EST 2006
s99999999s2003 at yahoo.com wrote:
> hi
>
> 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
For gigantic files (i.e. can't put all in RAM at once)
just make sure you always remember the previously read line.
Something like this:
old = None
f = open('mybigfile.txt')
for line in f:
if line == '12345678\n':
print old,
print line,
print f.next(),
old=line
More information about the Python-list
mailing list