CSV没有阅读

时间:2016-03-23 15:26:23

标签: python csv

我有一个包含我的代码的CSV文件,该文件包含在图像中。问题在于写入CSV文件的部分。它要么是因为不让我写入文件,要么说CSV不可读。

enter image description here

import csv

def checkstock():
    print('''The products that can be stocked are:
Apples    : 46527851
Chickens  : 39647511
Oranges   : 46912848
Toys      : 63891379
Pens      : 46873262
Water     : 38509162''')

    barcode=input('Please enter the GTIN of the product you want to check the stock for: ')
    with open('Stock.csv', 'r') as data:
        file=csv.reader(data)
        for row in file:
            if barcode in row:
                product1=row
                print(product1)

    name=product1[0]
    box=int(product1[1])
    currentstock=int(product1[2])
    minstock=int(product1[3])
    orderbox=int(product1[4])
    barcode=int(product1[5])

    needstock=int(currentstock-minstock)
    list3=[]
    if needstock <= 0:
        print('Order needed for pens, please order ' + orderbox + 'boxes of' + name)
        with open('Stock.csv', 'w') as data:
            file=csv.reader(data)
            list3.extend(file)
            overwrite={line[product1,'Yes']}
            with open('Stock.csv', 'w') as data:
                writer = csv.writer(data)
                for line, row in enumerate(list3):
                    data1 = overwrite.get(line, row)
                    writer.writerow(data1)

    else:
        print('The current level of ' + name + ' is sufficient.')
        with open('Stock.csv', 'w') as data:
            file=csv.reader(data)
            list3.extend(file)
            overwrite={line[product1,'No']}
            with open('Stock.csv', 'wb') as data:
                writer = csv.writer(data)
                for line, row in enumerate(list3):
                    data1 = overwrite.get(line, row)
                    writer.writerow(data1)

    repeat=input('Would you like to check the stock of another item? (Y or N) ')
    if repeat == 'Y':
        checkstock()
    if repeat == 'N':
        start()



    choice=input('''Would you like to either:      (Please enter a capial letter)
    (A) Check stock,
    (B) Record a delivery of products or,
    (C) See what needs to be delivered or,
    (D) Update a stock level: ''')

    if choice == 'A':
         checkstock()
    if choice == 'B':
        recStock()
    if choice == 'C':
        inOrder()

1 个答案:

答案 0 :(得分:0)

我没有理解代码,但我可以看到一些问题:

with open('Stock.csv', 'w') as data:
        file=csv.reader(data)
        list3.extend(file)
        overwrite={line[product1,'Yes']}

您无法使用&#39; w&#39;制作csv.reader。访问文件。 你只能有一个csv.writer() 另外,我建议不要用csv写入你正在阅读的文件。

你想用读/写部分做什么?