-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlast_n_lines.py
More file actions
45 lines (44 loc) · 2 KB
/
last_n_lines.py
File metadata and controls
45 lines (44 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import os
def get_last_n_lines(file_name, N):
# Create an empty list to keep the track of last N lines
list_of_lines = []
# Open file for reading in binary mode
with open(file_name, 'rb') as read_obj:
# Move the cursor to the end of the file
read_obj.seek(0, os.SEEK_END)
# Create a buffer to keep the last read line
buffer = bytearray()
# Get the current position of pointer i.e eof
pointer_location = read_obj.tell()
# Loop till pointer reaches the top of the file
while pointer_location >= 0:
# Move the file pointer to the location pointed by pointer_location
read_obj.seek(pointer_location)
# Shift pointer location by -1
pointer_location = pointer_location -1
# read that byte / character
new_byte = read_obj.read(1)
# If the read byte is new line character then it means one line is read
if new_byte == b'\n':
# Save the line in list of lines
list_of_lines.append(buffer.decode()[::-1])
# If the size of list reaches N, then return the reversed list
if len(list_of_lines) == N:
print("list_of_lines", list_of_lines)
return list(reversed(list_of_lines))
# Reinitialize the byte array to save next line
buffer = bytearray()
else:
# If last read character is not eol then add it in buffer
buffer.extend(new_byte)
# As file is read completely, if there is still data in buffer, then its first line.
if len(buffer) > 0:
list_of_lines.append(buffer.decode()[::-1])
# return the reversed list
print("list_of_lines", list_of_lines)
return list(reversed(list_of_lines))
last_lines = get_last_n_lines("sample.txt", 3)
print('Last 3 lines of File:')
# Iterate over the list of last 3 lines and print one by one
for line in last_lines:
print(line)