sowji
sowji

Reputation: 43

read previous lines from specific line in a file using python

I want to read the previous lines in a file from specific file. For example, this is my file content.

Line 1
Line 2
Line 3
Line 4
Line 5

I found a line "line 4" using some code. Now from line 4, I want to read the all previous lines in the order of

Line 3
Line 2
Line 1

How to achieve this???

Upvotes: 2

Views: 1207

Answers (3)

Martin Evans
Martin Evans

Reputation: 46779

A Python deque is ideal for doing this:

from collections import deque

last_lines = deque(maxlen=3)

with open('input.txt') as f_input:
    for line in f_input:
        line = line.strip()

        if line == 'Line 4':
            print list(reversed(last_lines))
            break

        last_lines.append(line)

This will display:

['Line 3', 'Line 2', 'Line 1']

It provides you with a fixed length queue. Every item you add to it causes the oldest item to be removed once maxlen items have been added. In your case it will mean you will only ever store 3 item in memory at once.

The same approach can be done with nornal lists but are not as fast.

Upvotes: 2

farbiondriven
farbiondriven

Reputation: 2468

Dirty but it does not store a list of strings:

p=0
with open("file") as fp:
    for i, line in enumerate(fp):
        if line==('Line 4'):
            p=i
for i in range(p,0):
    line = linecache.getline("file", i)    

Upvotes: 1

galaxyan
galaxyan

Reputation: 6141

you need to load file first then print it out

  with open(file_name, 'rb') as f:
    for line in f:
      if find_line_you_want_func(line):
        break
      res.append(line)
  for line in res[::-1]:
    print line

Upvotes: 1

Related Questions