0

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.

Val
  • 207,596
  • 13
  • 358
  • 360
user1801733
  • 147
  • 1
  • 3
  • 11

3 Answers3

3

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.

Example

$ python . <input >output 

Input

XYZ 1
2
3
4
XYZ 5
XYZ 6
7
8
9
XYZ 10
11
12

Output

3
4
4
XYZ 5
8
9
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

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)

0

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]
iimos
  • 4,767
  • 2
  • 33
  • 35