获取文件的最后n行,类似于tail [英] Get last n lines of a file, similar to tail
本文介绍了获取文件的最后n行,类似于tail的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为Web应用程序编写日志文件查看器,为此,我想在日志文件的各行中进行分页.文件中的项目是基于行的,底部是最新的项目.
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 on the bottom.
所以我需要一个tail()
方法,该方法可以从底部读取n
行并支持偏移量.我想到的是这样的:
So I need a tail()
method that can read n
lines from the bottom and supports an offset. What I came up with looks like this:
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?
推荐答案
我最终使用的代码.我认为这是迄今为止最好的:
The code I ended up using. I think this is the best so far:
def tail(f, n, offset=None):
"""Reads a n lines from f with an offset of offset lines. The return
value is a tuple in the form ``(lines, has_more)`` where `has_more` is
an indicator that is `True` if there are more lines in the file.
"""
avg_line_length = 74
to_read = n + (offset or 0)
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], \
len(lines) > to_read or pos > 0
avg_line_length *= 1.3
这篇关于获取文件的最后n行,类似于tail的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文