Python 中的列表索引超出范围错误(读取 CSV 文件)

list index out of range error in Python ( reading CSV file)

我正在尝试使用程序方法而不是面向对象的方法在 Python 中创建一家商店,然后我创建了这个函数来读取我的 CSV 文件和商店库存,除了 CSV 的第一行包含商店中“可用现金”的文件。

我当时试图访问价格和数量,但出现错误:

p=(row[0], float(row[1]))
IndexError: list index out of range

这是我的参考代码:

def createAndStockShop():
    s=Shop()
    with open("Stock.csv")as csv_file:#reading our stock file 
        csv_reader=csv.reader(csv_file,delimiter=',')#creating csv reader variable setting up delimiter as ","
        first_row=next(csv_reader)
        s.cash=(first_row[0])#extracting shop cash from first row of the file
        for row in csv_reader:#using for loop to go through the file 
            p=(row[0], float(row[1]))
            ps=ProductStock(p,float(row[2]))
            s.stock.append(ps)
            print(ps)
    return s#returning shop

作为参考,这是文件“Stock.csv”的样子: csv file I am opening in with this code and containing my stock

此外,这些是 类 我为产品库存和商店创建的以提供更多背景信息:

@dataclass #Creating first data class for Products in shop
class Product:
    name: str #values are "name" as string and price as float to include decimals
    price: float = 0.0

@dataclass #Creating data class for the stock in shop
class ProductStock:
    product:Product
    quantity:int

@dataclass #Dataclass for shop, values cash as a float and stock as list
class Shop():
    cash: float = 0.0
    stock: List[ProductStock] = field(default_factory=list)

根据您发布的图片...第 9,10 行是空行。删除它们并重试。

非常感谢你们,最后我按照你的建议删除了文件中的空行并且成功了!!非常感谢。但是现在告诉我一个不同的错误: ''' " 第 126 行,在 checking_stock if item.product.name == prod.product.name and item.quantity <= prod.quantity:#检查列表中的项目名称是否与库存名称匹配 AttributeError: 'tuple' 对象没有属性 'name'"

''' 我理解是指这段代码:

#defining method to check the shop stock: 
def checking_stock(c, s): #parameters for this function will be "c" ( customer) and s (shop)
    for item in c.shopping_list:#looping through the items in customer shopping list 
        for prod in s.stock:
                if item.product.name == prod.product.name and item.quantity <= prod.quantity:#checking if item name in list matches the name in stock
                    #also if quantity needed is less than the amount or product in stock
                    print(item, item.quantity, prod.quantity)#if this is the case, print item quantity and agree with the purchase
                    print("\nPerfect! you can proceed.")
                
                elif item.product.name == prod.product.name and item.quantity > prod.quantity:#else if the product amount requested by client is bigger than stock
                    print(f"Hey! So sorry! We do not have enough stock of: {item.product.name}, please select a different amount.")#printing error message
                    main()

如前所示,我为 Product 创建的 class 有一个属性名称:

@dataclass #Creating first data class for Products in shop
class Product:
    name: str #values are "name" as string and price as float to include decimals
    price: float = 0.0

跟这个有关系吗?非常感谢。