DictReader在csv中找到匹配但得到误报

时间:2017-01-13 16:41:27

标签: python-3.x csv

我正在编写一个Python3.x脚本来匹配大型CSV文件中的某些文本。我非常接近得到我正在寻找的东西,但由于某种原因我得到了误报。以下是我的代码:

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

预期产出:

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

相反,它找到了我正在寻找的集群,但也返回The cluster cannot be found

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

else条件仅针对col的最后一个值进行检查,如果不匹配则打印无法找到群集。您应该使用布尔变量来检查是否已找到群集

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