我复制了这个从文件
读取最后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”,那么我需要append
和prepend
\n
到单词error
以便我的行错误与其余部分分开
答案 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:])