我想在长的.json loggly文件中搜索特定的字符串,包括其行号,还想在搜索到的行的上方和下方打印5行。你能帮助我吗?
它总是返回“找不到”。
在此之后,我现在只能通过下面显示的程序获得一些输出。
与open('logg.json','r')为f:
对于ln,在enumerate(f)中的行:
如果“ error CRASHLOG”行中:
i = ln-25
对于(ln-25,ln + 25)中的i:
l = linecache.getline('logg.json',i)
i + = 1
打印(ln,l)
打印(“下一个错误”)
最佳答案
file.readlines()
返回行列表。行确实包含换行符(\n
)。
您需要指定换行符以匹配该行:
ln = data.index("error CRASHLOG\n")
如果要查找包含目标字符串的行,则需要迭代这些行:
with open('logg.json', 'r') as f:
for ln, line in enumerate(f):
if "error CRASHLOG" in line:
# You now know the line index (`ln`)
# Print above/below 5 lines here.
break
else:
print("Not Found")
顺便说一句,使用
grep(1)
可以轻松完成这种工作:grep -C 5 'error CRASHLOG' logg.json || echo 'Not Found'
更新
以下是更完整的代码:
from collections import deque
from itertools import islice, chain
import sys
with open('logg.json', 'r') as f:
last_lines = deque(maxlen=5) # contains the last (up to) 5 lines.
for ln, line in enumerate(f):
if "error CRASHLOG" in line:
sys.stdout.writelines(chain(last_lines, [line], islice(f, 5)))
last_lines.append(line)
else:
print("Not Found")
关于python - .json Loggly文件的Python编程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22166414/