Index Error: List out of range in Python vscode

Index Error: List out of range in Python vscode

我是学生,Python 三层架构的新手。我只是想按照我教授的示例代码

我收到以下错误:

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

下面是我正在处理的代码,我的数据在我的 csv 文件中如下:

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

代码从下面开始:

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)

谢谢 初学者

我无法测试它,但我认为你在文件中写入了错误的数据,之后读取它会出现问题。

你有

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

在末尾使用 writerows 和 char s - 但它需要像

这样的行列表
[ [...row1...], [...row2...], ...]

但是你用了 ['1','2','3','4'] .

因为字符串可以被视为字符列表,所以它被视为 [ ['1'], ['2'], ['3'], ['4'] ] 并在第一行写入 1,在第二行写入 2,依此类推。然后它读取具有一个元素的行 [ '1' ],以及具有一个元素的行 [=21] =] 但你期望行有四个元素 - 这会在 Customer(row[0], row[1], row[2], float(row[3]))

中产生问题

你应该使用不带字符的 writerow s 将其写为单行

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

编辑:

确保您在阅读时也可以检查行

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))