如何改进这一点以便CSV文件可以找到ID?

时间:2016-03-14 08:55:24

标签: python function csv

为什么这个程序无法运行它告诉我项目无法找到,即使它在CSV文件中它不想在所有梗塞中找到代码它也找不到任何东西我总是找不到它也不关心如果我按Y继续它不关心如果我按L它仍然会继续。

print(" Description    Product ID    Price")
import csv
f = open('CSVExelStockControlTask2.csv')
stock = csv.reader(f)
stocklist = []

for each in stock:
    print(each)


print("This is the list of what we have in-stock")


instock = []
outofstock = []


Repeat = True
found = False
while Repeat == True:
    item = int(input('Enter a GTIN Code of the item you want to add: '))

    for thing in stock:


        name = thing[0]
        GTIN = thing[1]

        if GTIN == item:
            found = True
            temp = []
            print ('\nItem Found',name , '-' ,GTIN ,'\n')
            temp.append(item)
            temp.append(GTIN)
            instock.append(temp)

    if found == False:
        print ('Item Was Not Found') 
        outofstock.append(item)

    Cont = input('\nAdd another item?')
    if Cont == 'N' or Cont == 'n':
        Repeat=False

print ('\nItem Selected')
for each in instock:
    print (each)

print ('\nItems not found')
for each in outofstock:
    print(each)

它应该是这样的:

Description    Product ID    Price
['100mm Bolts', '54378438', '0.5']
['Plain Brackets', '17578455', '2']
['Mounting Screws', '84257420', '3']
['Alarm Clock', '46325754', '6']
['Hedgehog Chushin', '22541529', '400']
['Bambo Couch', '17613422', '350']
['Wooden King Bed Frame', '45632464', '150']
['Mirror', '23454323', '75']
['Door', '36546756', '56']
['Window', '36546541', '30']
This is the list of what we have in-stock
Enter a GTIN Code of the item you want to add: 36546541
Item Was Found

Add another item?N

Item Selected
36546541
Items not found

但它提出了这个:

 Description    Product ID    Price
['100mm Bolts', '54378438', '0.5']
['Plain Brackets', '17578455', '2']
['Mounting Screws', '84257420', '3']
['Alarm Clock', '46325754', '6']
['Hedgehog Chushin', '22541529', '400']
['Bambo Couch', '17613422', '350']
['Wooden King Bed Frame', '45632464', '150']
['Mirror', '23454323', '75']
['Door', '36546756', '56']
['Window', '36546541', '30']
This is the list of what we have in-stock
Enter a GTIN Code of the item you want to add: 36546541
Item Was Not Found

Add another item?N

Item Selected

Items not found
36546541

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

检查失败的原因是CSV模块将所有内容都读为字符串。您说item = int(input(...然后与if GTIN == item:进行比较。这将始终失败,因为int永远不会比较等于字符串。要解决此问题要么与if int(GTIN) == item进行比较,要么不转换为int(请改用item = input(...)。

另一个问题是两次迭代stock。在第二个循环中它根本不会运行。您需要将其读入列表。使用stock = list(csv.reader(f))