Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IndexError: list index out of range for CSV

I am currently working on an Inventory System, and have just developed code that allows me to add items to my .csv

My current csv file looks like this:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my relevant code:

class CsvReader:
    def __init__(self): 
        self.result = []

    def make_dict_items(self):
        #fn = os.path.join('subdir', "Items2.csv")
        with open("Items2.csv") as fp:
            reader = csv.reader(fp)
            labels = next(reader, None)
            result = []
            for row in reader:
                row[0] = int(row[0])
                row[1] = float(row[1])
                row[2] = int(row[2])
                pairs = zip(labels, row)
                self.result.append(dict(pairs))

    def show_available(self):
        for item in self.result:
           print(item)
        
    def add_item(self):
       item_num = int(input("What is the items #?\n"))
       price = float(input("What is the items price?\n"))
       quant = int(input("What is the items quantity?\n"))
       name = input("What is the items name?\n")
       new_row = [item_num, price, quant, name]
       with open("Items2.csv", "a+") as  fp:
           reader = csv.reader(fp)
           fp.seek(0)
           labels = next(reader, None)
           writer = csv.writer(fp)
           new_record = dict(zip(labels, new_row))
           self.result.append(new_record)
           writer.writerow(new_record.values())

From what I understand, my add item is able to successfully input into my csv. For example, if I input 1, 2.99, 3, and Pumpkin into the inputs, and print(system.result), I can see the new dictionary in the list, and visually see it if I were to open the csv document.

What I dont understand is my current error I am getting. When I try to view my new item with my existing method that shows all items, I get an error:

row[0] = int(row[0])
IndexError: list index out of range

I understand this error has to do with trying to call elements in a list that don’t exist, but what seems to be the issue here. Why when I have the four items in my csv, the code works fine, but when I add a new row into the csv file, the code fails? Why does that specific line in make_dict_items not work when a 5th item is added, but works with the beginning four?

Code doesnt with with new inputted item

>Solution :

Your CSV has blank lines, which create empty row. Check for this and skip it.

            for row in reader:
                if row:
                    row[0] = int(row[0])
                    row[1] = float(row[1])
                    row[2] = int(row[2])
                    pairs = zip(labels, row)
                    self.result.append(dict(pairs))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading