clarkus978
clarkus978

Reputation: 634

DictReader finding match in csv but getting false positive

I'm writing a Python3.x script to match certain text in a large CSV file. I'm very close to getting what I'm looking for, but for some reason I'm getting a false positive. Below is my code:

from csv import DictReader

def cluster_lookup():
    cluster = input("What cluster are you looking for? ")
    while True:
        try:
            with open('hypervisor.csv') as csvfile:
                reader = DictReader(csvfile)
                for col in reader:
                    if col['cluster_name'] == cluster:
                        print(', '.join([col['host_name'], col['ip']]))
                        continue
        except IOError as err:
            print('Could not locate the csv file.', err)
            break
        else:
            if col['cluster_name'] is not cluster:
                print('The cluster cannot be found.')
                break

Expected output:

What cluster are you looking for? cluster 15
server150, 192.x.x.x
server151, 192.x.x.x
server152, 192.x.x.x
server153, 192.x.x.x
server154, 192.x.x.x
server155, 192.x.x.x
server156, 192.x.x.x
server157, 192.x.x.x
server158, 192.x.x.x
server159, 192.x.x.x

Instead it's finding the cluster I'm looking for but also returns The cluster cannot be found

Upvotes: 0

Views: 50

Answers (2)

thejonger
thejonger

Reputation: 91

def cluster_lookup():
   cluster = input("What cluster are you looking for? ")
   try:
       with open('hypervisor.csv') as csvfile:
           reader = DictReader(csvfile)
           isFound = False
           for col in reader:
               if col['cluster_name'] == cluster:
                   print(', '.join([col['host_name'], col['ip']]))
                   isFound = True
           if(isFound == False):
               print('The cluster cannot be found.')
               exit()
   except IOError as err:
       print('Could not locate the csv file.', err)
       exit()

Upvotes: 1

Tapan Chugh
Tapan Chugh

Reputation: 354

The else condition checks only against the last value of col, which if does not match prints The cluster cannot be found. You should instead use a boolean variable which checks if the cluster has been found or not

found = False
try:
   with open('hypervisor.csv') as csvfile:
   reader = DictReader(csvfile)
   for col in reader:
        if col['cluster_name'] == cluster:
           print(', '.join([col['host_name'], col['ip']]))
           found = True
           continue
except IOError as err:
        print('Could not locate the csv file.', err)
        break
    else:
        if not found:
            print('The cluster cannot be found.')
            break

Upvotes: 0

Related Questions