How to use csv as instance attritubes in python?

Viewed 20

How do I import csv file and use it as instance attributes for my class?

Here is the code ive written:

import random
import csv 

class Cars:
    
    def __init__(self, driver, team):
        self.driver = driver
        self.team = team
    

class Race:
    def __init__(self, lap = 55):
        self.lap = lap
        self._finished = []
        
    def race(self, list_of_cars):
        for c in list_of_cars:
            c.distance = 0
            
        while list_of_cars:
            for c in list_of_cars:
                c.distance += random.randint(100,300)
                if c.distance >= self.lap:
                    self._finished.append(c)
                    list_of_cars.remove(c) 
            
    def print_results(self):
        print("Tournament Result\n" + "_" * 18)
        for i, c in enumerate (self._finished):
            print (i+1, c.driver, c.team)
            
cars_list = []
with open("driverandteam.csv",'r') as file:
    csv_reader = csv.reader(file)
    for line in csv_reader:
        cars_list.append(Cars(line[0],line[1]))


r = Race(65)
cars = cars_list
r.race(cars)
r.print.results()

driverandteam.csv looks like this

Verstappen, Red Bull
Perez, Red Bull
Hamilton, Mercedes
Bottas, Mercedes
Leclerc, Ferrari
Sainz, Ferrari
Ricciardo, McLaren
Norris, McLaren
Ocon, Alphine
Alonso, Alphine
Tsunoda, AlphaTauri
Gasly, AlphaTauri
Vettel, Aston Martin
Stroll, Aston Martin
Latifi, Williams
Russell, Williams
Raikkonen, Alfa Romeo
Giovinazzi, Alfa Romeo
Mazepin, Haas
Schumacher, Haas

I keep getting "list of out range" error in line 36 of my code but im not understanding why. How can I fix my code so it works.

1 Answers

I ran your code locally and with the provided csv (thanks for providing all the needed info!), I had to make one small code change at the end:

r.print_results()

After that it all ran as expected and I got the following output:

Tournament Result
__________________
1 Verstappen  Red Bull
2 Hamilton  Mercedes
3 Leclerc  Ferrari
4 Ricciardo  McLaren
5 Ocon  Alphine
6 Tsunoda  AlphaTauri
7 Vettel  Aston Martin
8 Latifi  Williams
9 Raikkonen  Alfa Romeo
10 Mazepin  Haas
11 Perez  Red Bull
12 Sainz  Ferrari
13 Alonso  Alphine
14 Stroll  Aston Martin
15 Giovinazzi  Alfa Romeo
16 Bottas  Mercedes
17 Gasly  AlphaTauri
18 Schumacher  Haas
19 Norris  McLaren
20 Russell  Williams

So I'm unable to reproduce the error you're receiving, let us know if you're still encountering this error and can update any code/data to help reproduce.

Related