2016-07-07 136 views
0

我想寫一個代碼,我可以從不同的文件中搜索某些關鍵字;如果找到打印行和主機名;否則找不到打印「考試合格」和主機名如果發現關鍵字打印行其他打印python

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") 

它返回正確的搜索結果,但對於所有線路它亙古不變的查找關鍵字打印「考試合格」,輸出I在找的是

router 1 
not ready is ready 
reset me if required 

router 2 
test passed 
+0

只是使它成爲字符串;只是作爲一個例子寫的;所以請原諒這些錯誤;只需要找到一個可以執行的邏輯 – Saadi381

回答

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") 
+0

不工作;其印刷測試通過後,每個主機結果.. – Saadi381

+0

@ Saadi381對不起,我忘了在代碼中添加testpassed = False,現在編輯代碼,它應該工作 – Hani

+0

精湛...工作像一個魅力 – Saadi381