Reputation: 167
I am looping over all lines one by one using
line = file.readline()
Every line is now searched for a particular string(XYZ) -
line.startswith('XYZ')
I am not able to figure out how to get to couple of lines behind relative to the line where match was found for the string XYZ
.
I understand that this could be something trivial but couldn't make it.
Upvotes: 0
Views: 668
Reputation: 414655
You could use collections.deque()
to cache previous 2 lines:
#!/usr/bin/env python
import sys
from collections import deque
cached_lines = deque(maxlen=2) # keep 2 lines
for line in sys.stdin:
if line.startswith('XYZ'):
sys.stdout.writelines(cached_lines)
cached_lines.append(line)
The advantage is that you don't need to read the whole file into memory.
$ python . <input >output
XYZ 1
2
3
4
XYZ 5
XYZ 6
7
8
9
XYZ 10
11
12
3
4
4
XYZ 5
8
9
Upvotes: 3
Reputation: 5037
You need to save all readed lines or simply use readlines
method.
lines = file.readlines()
for i in range(0, len(lines)):
if lines[i].startswith("XYZ"):
print lines[i-2]
print lines[i-1]
Upvotes: 0
Reputation: 26
file.tell() gives current file pointer. And file.seek(pointer) sets the file pointer to given pointer. Like below code,
pointer = file.tell()
..
..
..
file.seek(pointer)
Upvotes: 0