如何让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
现在这完全正常,除了如何删除&#34; .log&#34;从每一行开始,这对其他用户更有意义吗?
有关我尝试做的更多信息:
我在这里有一系列日志文件:
日志\
在&#34; log&#34;目录,我有一堆日志文件,如下所示:
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"
/>
它可能是&#34; HOST_POWER =&#34; ON&#34;或&#34; HOST_POWER =&#34; OFF&#34;
然后编译如下摘要:
server1.web.com = ON
server2.web.com = ON
server3.web.com = OFF
server4.web.com = ON
server5.web.com = ON
答案 0 :(得分:1)
在print
来电中,将file
更改为file[:-4]
。除了最后4个字符'.log'。