user1801733
user1801733

Reputation: 167

Reading lines backwards relative to a line in python

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

Answers (3)

jfs
jfs

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.

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

Upvotes: 3

iimos
iimos

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

vishsangale
vishsangale

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

Related Questions