相关疑难解决方法(0)

使用Python获取文件的最后n行,类似于tail

我正在为Web应用程序编写一个日志文件查看器,为此我想通过日志文件的行分页.文件中的项目是基于行的,底部是最新项目.

所以我需要一种tail()方法,可以n从底部读取行并支持偏移量.我想出的是这样的:

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 …
Run Code Online (Sandbox Code Playgroud)

python file-io file tail logfiles

174
推荐指数
10
解决办法
14万
查看次数

如何使用python有效地跳过文件中的前n行?

我目前正在使用带有Python包装器的C++脚本来逐行操作更大的(15 GB)文本文件.它的作用实际上是从input.txt读取一行,处理它,将结果输出到output.txt.我在这里使用straigtforward循环(inp被打开为input.txt,out作为output.txt打开):

for line in inp:
    result = operate(line)
    out.write(result)
Run Code Online (Sandbox Code Playgroud)

但是,由于C++脚本的问题,它有一些失败率,导致循环在大约一千万次迭代后关闭.这给我留下了一个仅使用10%输入的输出文件.

由于我无法修复原始脚本,所以我只想重新启动它停止的地方.我计算了output.txt的行,创建了另一个名为output2.txt,并启动了以下代码:

k = 0
for line in inp:
    if k < 12123253:
        k + = 1
    else:
        result = operate(line)
        out2.write(result)
        k + = 1
Run Code Online (Sandbox Code Playgroud)

然而,与我计算在一分钟内结束的线路相比,这种方法需要很长时间才能到达指定的线路.

为什么这种方法效率低下?有更快的吗?我在Windows PC上具有强大的计算能力(72GB RAM,良好的处理器),并使用python 2.7.

python

0
推荐指数
1
解决办法
843
查看次数

标签 统计

python ×2

file ×1

file-io ×1

logfiles ×1

tail ×1