DeaD_EyE icon

rfind with mmap

DeaD_EyE | PRO | 09/15/22 12:40:28 PM UTC | 0 ⭐ | 1213 👁️ | Never ⏰ | []
Python |

650 B

|

None

|

0 👍

/

0 👎

import mmap
import os
 
 
def file_last(file, count):
    with open("log.txt") as log:
        end = last_pos = os.stat("log.txt").st_size
        lines = []
 
        with mmap.mmap(log.fileno(), 0, access=mmap.ACCESS_READ) as mm:
            while last_pos != -1:
 
                last_pos = mm.rfind(b"\n", 0, last_pos)
 
                if last_pos != -1:
                    lines.append(mm[last_pos:end].strip().decode())
                    end = last_pos
 
                if len(lines) >= count:
                    break
 
    lines.reverse()
    return lines
 
 
last_lines = file_last("log.txt", 3)
for line in last_lines:
    print(line)

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎