【问题标题】:list index out of range error in Python ( reading CSV file)Python中的列表索引超出范围错误(读取CSV文件)
【发布时间】:2022-01-17 06:14:41
【问题描述】:

我正在尝试使用程序方法而不是面向对象的方式在 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

此外,这些是我为 Product stock 和 shop 创建的类以提供更多上下文:

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

【问题讨论】:

  • 那么,row 中有什么内容?
  • 为什么不直接打印row 看看为什么row[0]row[1] 会失败?
  • 您的 CSV 文件中很可能存在空值/行。在代码中读取这些值时,会导致错误。
  • 请不要发布数据图像 - 将其复制并粘贴为文本,然后将其格式化为代码。通常,我们需要复制您的数据来测试您的代码和测试我们的解决方案——我们不能用图像来做到这一点。

标签: python csv python-dataclasses


【解决方案1】:

非常感谢你们,最后我按照你们的建议删除了文件中的空行,它起作用了!!非常感谢。但是现在告诉我一个不同的错误: ''' " 第 126 行,在检查库存中 if item.product.name == prod.product.name and item.quantity

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

#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 创建的类有一个属性名称:

@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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 下次将 csv(或其他文件/数据)作为文本而不是图像发布。
    猜你喜欢
    • 2021-04-20
    • 2019-12-11
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多