![](/img/trans.png)
[英]IndexError: list index out of range in CSV file reading python
[英]list index out of range error in Python ( reading CSV file)
I am trying to create a shop in Python using a procedural approach rather than Object Oriented and then I created this function which reads my CSV file with the shop stock, except for the first row of the CSV file that contains the "cash available" in商店。
我试图然后访问价格和数量,但我得到了错误:
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 文件我正在使用此代码打开并包含我的股票
此外,这些是我为 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)
非常感谢你们,最后我按照您的建议删除了文件中的空行并且它起作用了。:非常感谢,但是现在告诉我一个不同的错误。 ''' " 第 126 行。如果 item.product.name == prod.product.name 和 item:quantity <= prod:quantity:#checking 列表中的项目名称是否与库存中的名称匹配 AttributeError: 'tuple' object没有属性“名称””
''' 我理解它指的是这段代码:
#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
跟这个有关系吗? 太感谢了。
根据您发布的图像...第 9,10 行是空行。 删除它们并重试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.