我正在尝试编写一个代码,我可以从不同的文件中搜索某些关键字;如果找到打印行和主机名;否则找不到打印“测试通过”和主机名
Hostsfile.txt
router1
router2
router1.txt
not ready is ready
reset me if required
blah
blahhh blahh
router2.txt
blah
blahhh blahh
代码
hosts = open((hostsfile) , "r")
keys = ['Not Ready','RESET']
hosts = [hosts for hosts in (hosts.strip() for hosts in open(hostsfile)) if hosts]
for host2 in hosts:
f = [f for f in (f.strip() for f in open("router1.txt")) if f]
for line in f:
for keywords in keys:
if keywords in line:
print (line)
file2.write (line)
elif:
file2.write("Test Passed")
它会返回正确的搜索结果,但对于找不到关键字的所有行打印“Test Passed”,我正在寻找的输出是
router 1
not ready is ready
reset me if required
router 2
test passed
答案 0 :(得分:2)
我认为这就是你要找的东西
如果通过
,它只会打印一次hosts = open((hostsfile) , "r")
keys = ['Not Ready','RESET']
hosts = [hosts for hosts in (hosts.strip() for hosts in open(hostsfile)) if hosts]
for host2 in hosts:
f = [f for f in (f.strip() for f in open("router1.txt")) if f]
testpassed = True
for line in f:
for keywords in keys:
if keywords in line:
print (line)
file2.write (line)
testpassed = False
if testpassed:
file2.write("Test Passed")