'Index Error: List out of range in Python vscode

I am student and new to Python three-tier architecture. I am just trying to follow my professor's example code

I am getting following error:

    customer = Customer(row[0], row[1], row[2], float(row[3]))
IndexError: list index out of range

Below is my code I am working on and my data is in my csv file as follows:

JACK,WHITE,1234,40000
TOM,FORD,3456,80000
SARA,JAMES,5678,15000
KATE,GREY,7896,30000

CODE BEGINS from Below:

import csv
from pathlib import Path
from business import Customer
import os, sys

class CustomerRepository:
    def __init__(self) -> None:
        current_dir=os.path.dirname(__file__)
        self.__FILENAME = os.path.join(current_dir,"customer.csv")

    @property
    def FILENAME(self):
        return self.__FILENAME

    def getCustomers(self):
        customers = []
        with open(self.__FILENAME,'r', newline = "")as file:
            reader = csv.reader(file)

            for row in reader:
                #print (row)'
                customer = Customer(row[0], row[1], row[2], float(row[3]))
                customers.append(customer)
                
        return customers

    def writeCustomers(self):
        with open(self.FILENAME, 'w', newline = "")as file:
            writer = csv.writer(file)
            new_line=['1','2','3','4']
            writer.writerows(new_line)
            customers=[[1,2,3,4], [2,3,4,5]]
            for row in customers:
                writer.writerow(row)

Thanks BeginnerCoder



Solution 1:[1]

I can't test it but I think you wrote wrong data in file and later it makes problem to read it.

You have

new_line = ['1','2','3','4']
writer.writerows(new_line)   # <--- with `s` 

which use writerows with char s at the end - but it needs list of rows like

[ [...row1...], [...row2...], ...]

but you usel lise ['1','2','3','4'] .

Because string can be treated as list of char so it treats as [ ['1'], ['2'], ['3'], ['4'] ] and it write 1 in first row, 2 in second row, etc. And later it read row with one element [ '1' ], and row with one element [ '2' ] but you expect rows with four elements - and this makes problem in Customer(row[0], row[1], row[2], float(row[3]))

You should use writerow without char s to write it as single row

new_line = ['1','2','3','4']
writer.writerow(new_line)    # <--- without `s`

EDIT:

To make sure you could also check rows when you read it

for row in reader:
    if len(row) == 4:
         customer = Customer(row[0], row[1], row[2], float(row[3]))
         customers.append(customer)
    else:
        print("wrong number of data in row:" row)
        print("it should have 4 elements but it has", len(row))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 furas