我正在创建一个python脚本,其中有2个名为dhcplist.csv的csv文件,以及actualuse.csv
两个csv文件都包含每行的IP地址:
例如:
dhcplist.csv:
192.168.0.11
192.168.0.22
192.168.0.35
192.168.0.41
192.168.0.59
actualuse.csv:
192.168.0.10
192.168.0.22
192.168.0.41
192.168.0.109
192.168.0.210
我要做的是比较每个csv文件中的行。如果两个文件之间的IP地址不匹配。我想打印出不匹配的IP地址。
我正在尝试类似的事情:
import csv
server_dhcp_file = "./dhcplist.csv"
actual_hosts_file = "./actualuse.csv"
server_dhcp_reader = csv.reader(open(server_dhcp_file, 'rU'))
actual_host_reader = csv.reader(open(actual_hosts_file, 'rU'))
for row1 in server_dhcp_reader:
for row2 in actual_host_reader:
if row1 != row2:
print row1[0] + " != " + row2[0]
else:
continue
但这给了我以下输出:
192.168.0.11 != 192.168.0.10
192.168.0.11 != 192.168.0.12
192.168.0.11 != 192.168.0.41
192.168.0.11 != 192.168.0.109
192.168.0.11 != 192.168.0.210
如何获取它以便它测试dhcplist.csv中的所有ip地址,而不仅仅是" 192.168.0.11"
非常感谢任何建议/意见
答案 0 :(得分:2)
您是在一个文件而不是另一个文件中寻找IP地址集,反之亦然?
with open(server_dhcp_file, 'rU') as f1, open(actual_hosts_file, 'rU') as f2
server_dhcp_reader = csv.reader(f1)
actual_host_reader = csv.reader(f2))
actual_host = {row[0] for row in actual_host_reader}
server_dhcp = {row[0] for row in server_dhcp_reader}
print "In actual but not server", actual_host - server_dhcp
print "In server but not actual", server_dhcp - actual_host
还要注意使用with
在我们完成文件后立即关闭文件
答案 1 :(得分:0)
删除第二个for
循环:
for row1 in server_dhcp_reader:
row2 = actual_host_reader.next()