Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在用python编写的tail函数中附加一些数据_Python_Linux - Fatal编程技术网

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

如何在用python编写的tail函数中附加一些数据,python,linux,Python,Linux,我复制了这个python函数,它从文件中读取最后n行 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): #

我复制了这个python函数,它从文件中读取最后n行

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”,那么我需要
在单词
error
后追加
前置
\n
,这样带错误的行与其余行分开这将
'\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:])

这会将
'\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:])

这是出现在行尾,而不是在单词后面。此外,如果这是类似于
Fielderror
的子字符串,则这不会捕获单词,因为它出现在行尾而不是单词后面。此外,如果这是类似于
Fielderror