简体   繁体   中英

Comparing 2 columns on CSV files

I am creating a python script where I have 2 csv files named dhcplist.csv, and actualuse.csv

Both csv files contains ip addresses on each row:

for example:

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

What I am trying to do is to compare the row on each csv file. If the IP address does not match between the 2 files. I want to print out the ip address that doesn't match.

I was trying something like:

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

But this gave me the following output:

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

How can I get it so that it tests all the ip addresses in dhcplist.csv, rather than only "192.168.0.11"

Any suggestions/advice would be much appreciated

Are you looking for the set of IP addresses in one file and not the other, and vice versa?

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

Note also the use of with to close the files as soon as we're done with them

Remove the second for loop:

for row1 in server_dhcp_reader:
    row2 = actual_host_reader.next()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM