2

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???

sowji
  • 43
  • 1
  • 6
  • 3
    Perhaps you could update your question with some code that reads lines from a file to show what problem you have? – quamrana Oct 13 '17 at 13:20
  • I can store the lines, but I have a large file not enough to store – sowji Oct 13 '17 at 13:23
  • 1
    It's not so trivial if you can't store it all in memory, but see this https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python – Chris_Rands Oct 13 '17 at 13:33
  • You need to specify just how big your input file is and how many lines you need to go back. So far you are getting answers that fulfil your exact example. – quamrana Oct 13 '17 at 13:41

3 Answers3

2

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.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
1

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
galaxyan
  • 5,944
  • 2
  • 19
  • 43
  • My file is too large to store in a list, can you tell me another possibility please – sowji Oct 13 '17 at 13:25
  • @LakshmisoujanyaGuthikonda do you want reversed the order or not? – galaxyan Oct 13 '17 at 13:26
  • yes, I want reversed order, from specific line in a file i want to fetch only few lines which are before that line, which means previous lines. – sowji Oct 13 '17 at 13:30
  • @LakshmisoujanyaGuthikonda I think you may need to write a function to reverse file https://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python – galaxyan Oct 13 '17 at 14:21
  • @LakshmisoujanyaGuthikonda the answer from srohde is the one you need – galaxyan Oct 13 '17 at 14:21
1

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)    
farbiondriven
  • 2,450
  • 2
  • 15
  • 31