Read the last 5 lines of a file through Python

Asked

Viewed 589 times

3

I asked that question here at Stackoverlow Display last 5 lines of a PHP file?

Now I wonder 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 to Python memory?

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 here.

  • this method is very complicated...

1

My suggestion includes using an iterator with for...in. This uses relatively little memory and remains quite readable, 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.