Advertisement
DeaD_EyE

rfind with mmap

Sep 15th, 2022
745
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.65 KB | None | 0 0
  1. import mmap
  2. import os
  3.  
  4.  
  5. def file_last(file, count):
  6.     with open("log.txt") as log:
  7.         end = last_pos = os.stat("log.txt").st_size
  8.         lines = []
  9.  
  10.         with mmap.mmap(log.fileno(), 0, access=mmap.ACCESS_READ) as mm:
  11.             while last_pos != -1:
  12.  
  13.                 last_pos = mm.rfind(b"\n", 0, last_pos)
  14.  
  15.                 if last_pos != -1:
  16.                     lines.append(mm[last_pos:end].strip().decode())
  17.                     end = last_pos
  18.  
  19.                 if len(lines) >= count:
  20.                     break
  21.  
  22.     lines.reverse()
  23.     return lines
  24.  
  25.  
  26. last_lines = file_last("log.txt", 3)
  27. for line in last_lines:
  28.     print(line)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement