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