👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!
I"m writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom.
So I need a tail()
method that can read n
lines from the bottom and support an offset. This is hat I came up with:
def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
Is this a reasonable approach? What is the recommended way to tail log files with offsets?
👻 Read also: what is the best laptop for engineering students?
We hope this article has helped you to resolve the problem. Apart from Get last n lines of a file, similar to tail, check other ast Python module-related topics.
Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.
By the way, this material is also available in other languages:
- Italiano Get last n lines of a file, similar to tail
- Deutsch Get last n lines of a file, similar to tail
- Français Get last n lines of a file, similar to tail
- Español Get last n lines of a file, similar to tail
- Türk Get last n lines of a file, similar to tail
- Русский Get last n lines of a file, similar to tail
- Português Get last n lines of a file, similar to tail
- Polski Get last n lines of a file, similar to tail
- Nederlandse Get last n lines of a file, similar to tail
- 中文 Get last n lines of a file, similar to tail
- 한국어 Get last n lines of a file, similar to tail
- 日本語 Get last n lines of a file, similar to tail
- हिन्दी Get last n lines of a file, similar to tail
Paris | 2023-03-29
I was preparing for my coding interview, thanks for clarifying this - Get last n lines of a file, similar to tail in Python is not the simplest one. I am just not quite sure it is the best method
Berlin | 2023-03-29
Simply put and clear. Thank you for sharing. Get last n lines of a file, similar to tail and other issues with Python functions was always my weak point 😁. I just hope that will not emerge anymore
Vigrinia | 2023-03-29
Maybe there are another answers? What Get last n lines of a file, similar to tail exactly means?. Checked yesterday, it works!