Read the last 5 lines of a file via Python

3

I asked this question here in Stackoverlow View the last 5 lines of a file with PHP?

Now I would like to know how I could do the same thing in Python.

How could I get the last 5 lines of a large file, without having to fully load it into memory in Python?

    
asked by anonymous 03.09.2015 / 22:59

2 answers

2

The most elegant solution I found (among the many that exist) is this:

def tail(f, n):
    assert n >= 0
    pos, lines = n+1, []
    while len(lines) <= n:
        try:
            f.seek(-pos, 2)
        except IOError:
            f.seek(0)
            break
        finally:
            lines = list(f)
        pos *= 2
    return lines[-n:]

I took it from .

    
03.09.2015 / 23:03
1

My suggestion includes using an iterator with for...in . This uses relatively little memory and remains quite legible, in my opinion.

def tail_file(file_name, number):
    lines = []
    with open(file_name) as f:
        for line in f:
            lines.append(line.rstrip())
            if len(lines) > number:
                lines.pop(0)
    return lines
    
04.09.2015 / 03:34