让 python 遍历日志文件并从每个文件中找到字符串

Have python loop through log files and find string from each one

如何让 Python 遍历目录并在该目录中的每个文件中找到特定的字符串,然后输出找到的内容的摘要?

我想在长文件中搜索电源状态 (HOST_POWER),它是 "ON" 或 "OFF"。

<GET_HOST_POWER
    HOST_POWER="ON"
    />

这是我目前的情况:

import glob
import os

print("The following list contains the power status of each server.\n")

os.chdir( "LOGS\" )
for file in glob.glob('*.log'):
    with open(file) as f:
        contents = f.read()
    if 'HOST_POWER="ON"' in contents:
        print (file + " = ON")
    if 'HOST_POWER="OFF"' in contents:
        print (file + " = OFF")

输出:

The following list contains the power status of each server.

server1.web.com.log = ON
server2.web.com.log = ON
server3.web.com.log = ON
server4.web.com.log = OFF
server5.web.com.log = ON

这现在工作得很好,除了如何从每一行中删除“.log”,以便它对其他用户更有意义?


有关我正在尝试做的事情的更多信息:

我在此处有一系列日志文件:

日志\

在"logs"目录中,我有一堆日志文件,如下所示:

server1.web.com.log
server2.web.com.log
server3.web.com.log
server4.web.com.log
server5.web.com.log

每个日志文件包含如下信息:

IP Address is: server1.web.com <?xml version="1.0"?> <RIBCL VERSION="2.22"> <RESPONSE
    STATUS="0x0000"
    MESSAGE='No error'
     /> </RIBCL> <?xml version="1.0"?> <RIBCL VERSION="2.22"> <RESPONSE
    STATUS="0x0000"
    MESSAGE='No error'
     /> </RIBCL> <?xml version="1.0"?> <RIBCL VERSION="2.22"> <RESPONSE
    STATUS="0x0000"
    MESSAGE='No error'
     /> </RIBCL> <?xml version="1.0"?> <RIBCL VERSION="2.22"> <RESPONSE
    STATUS="0x0000"
    MESSAGE='No error'
     /> <GET_HOST_POWER
    HOST_POWER="ON"
    /> </RIBCL> <?xml version="1.0"?> <RIBCL VERSION="2.22"> <RESPONSE
    STATUS="0x0000"
    MESSAGE='No error'
     /> </RIBCL> <?xml version="1.0"?> <RIBCL VERSION="2.22"> <RESPONSE
    STATUS="0x0000"
    MESSAGE='No error'
     /> </RIBCL> <?xml version="1.0"?> <RIBCL VERSION="2.22"> <RESPONSE
    STATUS="0x0000"
    MESSAGE='No error'
     /> </RIBCL>

iLO_config_utility\cpqlocfg.exe: Script succeeded on "server1.web.com:443"

我希望我的 Python 代码循环遍历每个日志文件并找到主机电源的状态:

<GET_HOST_POWER
    HOST_POWER="ON"
    />

它可以是“HOST_POWER="ON" 或“HOST_POWER="OFF"

然后编写如下摘要:

server1.web.com = ON
server2.web.com = ON
server3.web.com = OFF
server4.web.com = ON
server5.web.com = ON

print 调用中,将 file 更改为 file[:-4]。这会切掉除最后 4 个字符 '.log' 之外的所有内容。