用python和if语句搜索CSV文件

2024-06-17 12:10:41 发布

您现在位置: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)

Tags: ofcsvthecsvfileproductsrowgtinappend
1条回答
网友
1楼 · 发布于 2024-06-17 12:10:41

如果查找的值不存在,则需要try and except。以及一段时间的循环继续尝试!你知道吗

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

相关问题 更多 >