Categories
Python Answers

How to get last n lines of a file, similar to tail with Python?

Spread the love

Sometimes, we want to get last n lines of a file, similar to tail with Python.

In this article, we’ll look at how to get last n lines of a file, similar to tail with Python.

How to get last n lines of a file, similar to tail with Python?

To get last n lines of a file, similar to tail with Python, we can run tail with Popen.

For instance, we write

import subprocess

def tail(f, n, offset=0):
    proc = subprocess.Popen(['tail', '-n', n + offset, f], stdout=subprocess.PIPE)
    lines = proc.stdout.readlines()
    return lines[:, -offset]

to create the tail function that runs tail with the arguments to return the last n lines from file with path f.

And then we set stdout to subprocess.PIPE to return the output.

Next, we call proc.stdout.readlines to get the output and return it.

Finally, we use lines[:, -offset] to get the list with the last n lines.

Conclusion

To get last n lines of a file, similar to tail with Python, we can run tail with Popen.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *