我有一个日志文件(下面的示例),用于跟踪错误,警告和信息。我想在Python中创建一个仅提取错误的脚本。我想提取带有时间戳的标题和带有错误文本的行。
>>> Log file (e.g. logfile.log)
=====
2018-10-31 05:20:57.282 WARN
2018-10-31 05:20:57.331 WARN
2018-10-31 05:20:57.367 INFO
2018-10-31 05:20:57.367 ERROR
text
text
text
2018-10-31 05:20:57.367 INFO
>>> Expected results:
2018-10-31 05:20:57.367 ERROR
text
text
text
非常感谢您的帮助。
答案 0 :(得分:0)
file_in = open('logfile.log','r') # Read file
for line in file_in: # Loop every line
if 'ERROR' in line: # Search for ERROR in line
print(line) # Print line
elif 'INFO' not in line and 'WARN' not in line: # Remove INFO and WARN lines
print(line) # Print line