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???
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.
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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.