2016-08-04 132 views
-1

我有一個函數輸出的列表,我想驗證數組中的元素是否在文件(包含服務器名稱的文本文件)中,並且我想要只打印那些不在文件中的服務器。Python:驗證列表中的元素是否存在於文件中,如果不存在,則打印

在這些線路上的一些思考:

host_list = ['abc.server.com', 'xyz.server.com'] 
sfile = open("slist.txt","r") 
for num in host_list: 
     do 
      for aline in sfile.realines(): 
       if num =! aline.split() 
       print num 
sfile.close() 
+1

那麼究竟是什麼問題? – Mureinik

+1

'do'不是有效的Python語法。你也希望'!='而不是'=!'。並使用'with'塊來打開文件。 –

+1

實際上,您的代碼中有幾處拼寫錯誤。 –

回答

1

這裏有一個簡單的方法做你正在嘗試做的:

host_list = ['abc.server.com', 'xyz.server.com'] 
sfile = open("slist.txt","r") 
hosts_in_file = set() 
for line in sfile: 
    for server in line.strip().split(): 
    hosts_in_file.add(server) 

print [host for host in host_list if host not in hosts_in_file] 
sfile.close() 
+0

感謝它的工作。 – cloudvar

+0

你也可以感謝我upvote :) – bpachev

相關問題