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
.