IndexError:尝试使用CSV时列出索引超出范围

时间:2016-06-29 16:58:15

标签: python csv indexing range

我正在处理我正在编写的程序的CSV文件,但我似乎收到了这个错误:

Traceback (most recent call last):
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453 Material 2\Task 3\Task 3.py", line 115, in <module>
actionQ()
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453`Material 2\Task 3\Task 3.py", line 111, in actionQ
gtinQuestion()
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453 Material 2\Task 3\Task 3.py", line 80, in gtinQuestion
quantityQuestion() #It will start the quantityQuestion subprogram.
File "C:\Users\Jordan\Documents\Year 10\Computing\CA and Coursework\A453 Material 2\Task 3\Task 3.py", line 52, in quantityQuestion
if float(row[3]) >= float(quantity):
IndexError: list index out of range`

我不太确定如何接近它,但我之前从未遇到过这个问题。最初,quantityQuestion是它自己的程序,但我决定将其与其他代码一起放在可访问性中。

作为旁注 - 我无法覆盖第三行,以便可以在CSV中更新新库存。 (对此的任何帮助也表示赞赏)。

代码:

import csv
import sys

global totalPrice
totalPrice = 0

addItem = ""
gtinNum = ""
quantity = 0
restart = ""
price = 0

receipt = open("receipt.txt", "w+")
restockTxt = open("restock.txt", "w+")
file = open("ChocolateCSV2.csv", "r")

def restart():
    restart = input("Would you like to restart? Y/N")

    if restart.lower() == "y":
        actionQ()
    else:
        file.close()
        print("Exiting program.")
        sys.exit()

def priceSub(): #Defining the restart subprogram
    priceQ = input("Would you like to add an item? Y/N") #Asks the user if they would like to add an item.
    global totalPrice #Declaring totalPrice and making it global.
    totalPrice = int(price) + totalPrice #Setting totalPrice to add the variable price to itself.

    if priceQ.lower() == "y": #If statement that checks to see if the user has entered a "y".
        gtinQuestion() #If it is true, it will start the gtinQuestion subprogram.
    else: #Anything other than a "y" will do the following commands.
        global receiptCont #Declaring the receipt content as a global variable.
        receiptCont = receipt.read() #Reads the receipt.
        receipt.close() #Closes the file.
        print(receiptCont) #Prints the content of the receipt.
        print("Total Price: " + "%.2f" % round(totalPrice, 2)) #Prints the totalPrice variable rounded to two decimal places.
        restart()

def quantityQuestion(): #Defining the subprogram for the quantity.
    quantity = input("How much would you like?") #Asks the user how much of the item they would like.
    if quantity.isdigit() == False: #If statement to check whether or not the user has entered an integer or not.
        quantityQuestion() #If they have not entered an integer, it will ask the question again.
    global price #Declaring the variable price as a global variable.
    price = "" #Setting price to an empty string.

    with open("ChocolateCSV.csv", 'r') as file2:
        for row in csv.reader(file2): #Loop that seperates each row in the CSV
            if str(gtinNum) in row[0]: #If statement to check if the GTIN given by the user is in the CSV.
                if float(row[3]) >= float(quantity):
                    receipt.write(str(row) + "\n") #If it is in one of the CSV rows, it will write the row to the text file.
                    receipt.write(str("- Quantity: " + quantity + "\n")) #It also writes the quantity given by the user.
                    price = float(row[2]) * int(quantity) #The price is the price given by the CSV file multiplied by the quantity.
                    receipt.write("- Price: " + str("%.2f" % round(price, 2)) + "\n") #The final price (after the multiplication) is written to the text file also.
                    updateStk = str(float(row[3]) - float(quantity))
                    row[3] = updateStk
                    file2w = open("ChocolateCSV2.csv", "w", newline = "")
                    writeCSV = csv.writer(file2w)
                    writeCSV.writerows(csvList)
                    file2w.close()
                    priceSub() #Starts the restart subprogram.
                    break #Breaks the loop.
                elif float(row[3]) <= float(quantity):
                    print("There is not enough stock to allow you to purchase this item - Try again u nerd.")
                    gtinQuestion()
        else:
            print("The code entered could not be found - Please re-enter") #If it is not in the CSV it will print this error message.
            gtinQuestion() #Starts the gtinQuestion subprogram.

def gtinQuestion(): #Defining the gtinQuestion subprogram.
    global gtinNum #Declaring the gtinNum variable as global.
    gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:") #Setting that variable to the initial question.

    if gtinNum.isdigit() == False or len(gtinNum) != 8: #If the code given is not an integer or is not 8 digits long...
        print("Please re-enter your GTIN-8 code - Reason: Invalid Code") #It will print this error message and ask the question again.
        gtinQuestion()
    elif gtinNum.isdigit() == True and len(gtinNum) == 8: #If it is an integer and is 8 digits long...
        quantityQuestion() #It will start the quantityQuestion subprogram.

def restockAction():
    reader = csv.reader(file, delimiter = ",")
    csvList = list(reader)

    for row in csvList:
        stDiff = float(row[5]) - float(row[3])
        if float(row[3]) <= float(row[4]):
            restockTxt.write(row[0]+" | "+row[1]+" | "+"Stock Replenished: "+(str(stDiff)+"\n"))
            row[3] = row[5]
            file2w = open("ChocolateCSV2.csv", "w", newline = "")
            writeCSV = csv.writer(file2w)
            writeCSV.writerows(csvList)
            file2w.close()
    else:
            restockTxt.write("No (other) stock needs to be replenished.")
            restockTxt.close()
            restockRead = open("restock.txt", "r")                        print(restockRead.read())
            restart()


def actionQ():
restock = input("What action would you like to perform?:\n Restock (Enter 1)\n Order (Enter 2)")

    if restock == "1" or restock == "restock":
        print("Restock Action Requested...")
        restockAction()
    elif restock == "2" or restock == "order":
        print("Ordering action Requested...")
        gtinQuestion()
    else:
        actionQ()

actionQ()

CSV文件:

12312313    Item 1  0.5 100 25  100
12345670    Item 2  0.2 100 25  100
76543210    Item 3  0.3 100 25  100
34563670    Item 4  0.4 100 25  100

0 个答案:

没有答案