如何在python中编写的tail函数中附加一些数据

时间:2013-02-15 08:07:12

标签: python linux

我复制了这个从文件

读取最后n行的python函数
def tail(self, f, window=20 ):
    BUFSIZ = 1024
    f.seek(0, 2)
    bytes = f.tell()
    size = window
    block = -1
    data = []
    while size > 0 and bytes > 0:
        if (bytes - BUFSIZ > 0):
            # Seek back one whole BUFSIZ
            f.seek(block*BUFSIZ, 2)
            # read BUFFER
            data.append(f.read(BUFSIZ))
        else:
            # file too small, start from begining
            f.seek(0,0)
            # only read what was not read
            data.append(f.read(bytes))
        linesFound = data[-1].count('\n')
        size -= linesFound
        bytes -= BUFSIZ
        block -= 1
    return '\n'.join(''.join(data).splitlines()[-window:])

现在我想要的是,如果该行包含单词“error”,那么我需要appendprepend \n到单词error以便我的行错误与其余部分分开

1 个答案:

答案 0 :(得分:1)

这会将'\n'添加到包含字符串'error'的所有前面并加上

def segregate(lines, word):
    for line in lines:
        if word in line:
            yield '\n'+line+'\n'
        else:
            yield line

你可以像这样挂钩tail

def tail(f, window=20):
    ...
    return '\n'.join(segregate(''.join(data).splitlines()[-window:], 'error'))

如果您希望仅将'\n'添加到字符串'error',则可以改为使用re.sub

import re
def tail(f, window=20):
    ...
    return '\n'.join(re.sub(r'error', '\nerror\n', ''.join(data)).splitlines()[-window:])