使用带有if语句的python搜索CSV文件

时间:2017-02-16 15:29:55

标签: python

我一直在尝试在python中搜索我的csv文件,这样可以输出每个项目的成本等。但是如果输入错误的GTIN代码,我需要它说它找不到产品。需要帮助。非常感谢提前

import csv

with open('PriceList.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
GTINcode = []
Products = []
Quantitys = []
PricePu = []
Totals = []
for row in readCSV:
    Product = row[1]
    GTIN = row[0]
    Quantity = row[2]
    Total = row[4]
    Price = row[3]

    GTINcode.append(GTIN)
    Products.append(Product)
    Quantitys.append(Quantity)
    Totals.append(Total)
    PricePu.append(Price)
whatColor = input('Enter the GTIN code of the product you wish:')
coldex = GTINcode.index(whatColor)
theDate = Products[coldex]
info = Quantitys[coldex]
ppi = PricePu[coldex]
tts = Totals[coldex]

print('Your GTIN code of:',whatColor,'is',theDate,"We have",info,"left in      stock. The price for each item is",ppi,"and the total cost of this would be",tts)

1 个答案:

答案 0 :(得分:0)

如果查找的值不存在,则需要try and except。以及一个继续尝试的while循环!

import csv

with open('PriceList.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
GTINcode = []
Products = []
Quantitys = []
PricePu = []
Totals = []
for row in readCSV:
    Product = row[1]
    GTIN = row[0]
    Quantity = row[2]
    Total = row[4]
    Price = row[3]

    GTINcode.append(GTIN)
    Products.append(Product)
    Quantitys.append(Quantity)
    Totals.append(Total)
    PricePu.append(Price)
error = True
while error:
    whatColor = input('Enter the GTIN code of the product you wish:')
    try:
        coldex = GTINcode.index(whatColor)
        error = False
        theDate = Products[coldex]
        info = Quantitys[coldex]
        ppi = PricePu[coldex]
        tts = Totals[coldex]
        print('Your GTIN code of:',whatColor,'is',theDate,"We have",info,"left in      stock. The price for each item is",ppi,"and the total cost of this would be",tts)
    except ValueError:
        print('This is not a valid GTIN code')