2

我复制了这个从文件中读取最后 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:])

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

4

1 回答 1

2

这将附加并添加到包含字符串'\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:])
于 2013-02-15T08:27:08.490 回答