我在其中一台服务器上有一个日志文件,我需要编写一个python脚本来复制包含ERROR和INFO标记的行。我希望每次运行脚本时都将带有标签的所有行写入新文件。
这是我到目前为止所写的内容(我是新手)
my_errors=open("/var/tmp/myerrors1.txt", "w")
my_trace=open("/var/tmp/logs/trace1.txt", "r")
my_trace.readline()
x = [INFO, WARN, ERRor]
for line in my_trace:
for x in line:
my_errors.writelines(x)
my_errors.close()
my_trace.close()
trace1.txt示例:
03/17/2015 13:41:55|WARN||ajp-bio-127.0.0.1-4090-exec-5|495233559||_ERR: execute(): Error Response returned
03/17/2015 13:41:47|INFO||ajp-bio-127.0.0.1-4090-exec-2|495785359||_IN:SearchQuery getList(): ||||
答案 0 :(得分:0)
试试这个:
my_errors = open("/var/tmp/myerrors1.txt", "w")
my_trace = open("/var/tmp/logs/trace1.txt", "r")
levels = ['INFO', 'WARN', 'ERROR']
for line in my_trace:
if any(level in line for level in levels):
my_errors.write(line)
my_errors.close()
my_trace.close()
使用以下trace1.txt
文件进行测试:
03/17/2015 13:41:55|WARN||ajp-bio-127.0.0.1-4090-exec-5|495233559||_ERR: execute(): Error Response returned
Do not copy this line
03/17/2015 13:41:47|INFO||ajp-bio-127.0.0.1-4090-exec-2|495785359||_IN:SearchQuery getList(): ||||
Do not copy this line
myerrors1.txt
档案的结果:
03/17/2015 13:41:55|WARN||ajp-bio-127.0.0.1-4090-exec-5|495233559||_ERR: execute(): Error Response returned
03/17/2015 13:41:47|INFO||ajp-bio-127.0.0.1-4090-exec-2|495785359||_IN:SearchQuery getList(): ||||
编辑2:
my_errors = open("/var/tmp/myerrors1.txt", "w")
my_trace = open("/var/tmp/logs/trace1.txt", "r")
levels = ['INFO', 'WARN', 'ERROR']
for line in my_trace:
for level in levels:
if level in line:
my_errors.write(line)
my_errors.close()
my_trace.close()
答案 1 :(得分:0)
您还没有指定问题,但我认为您的问题是没有任何内容写入您的文件。您正在将x
重新分配给其他内容(line
中的值)。您需要为其分配一个不同的变量,如下所示:
my_errors=open("/var/tmp/myerrors1.txt", "w")
my_trace=open("/var/tmp/logs/trace1.txt", "r")
my_trace.readline()
x = [INFO, WARN, ERRor]
for line in my_trace:
for message in line: # change from reassigning the x variable to something else
for error in x: # iterating through the errors in x
if error in my_trace: # checking if an error is in my_trace
my_errors.writelines(error) # writing the error
my_errors.close()
my_trace.close()
当然,如果没有完整的信息,这不是最好的答案,但它应该是您可以修复代码的基础。