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 the shop.
I was trying to then access to price and quantity but I get the error:
p=(row[0], float(row[1]))
IndexError: list index out of range
This is my code for reference:
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
And for reference this is how the file "Stock.csv" looks: csv file I am opening in with this code and containing my stock
In addition these are the classes I have created for Product stock and shop to give some more context:
@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)
based on the image you have posted ... lines 9,10 are empty lines. Remove them and try again.