Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from csv into a python object

I am a beginner python user. Having trouble getting data from csv into python in the required object format to satisfy a python function. If I manually created the data in python (rather than bringing it in from csv) the following code works:

class Student(object):
   pass

john = Student()
#score tuple
john.score = (85.0, 42.0/2.0)

bob = Student()
bob.score = (45.0, 19.0/2.0)

john.rank = 1
bob.rank = 2

ExternalCode.AdjustStudents([john, bob])

However I need it to work automatically and not have to manually type out the data each time as there are going to be thousands of updates - hence the need to be able to bring in the data from csv.

The csv file format is: john, 85, 21, 1 bob, 45, 9.5, 2

Student objects would have a score attribute (columns 2 and 3 as a tuple) as well as a rank attribute (column 4). The required object format would be the same as produced by the manual code above.

An example of the required format produced by the manual code, is that when I do the following print after the manual code:

print(" John: score1={0[0]:.3f} score2={0[1]:.3f}".format(john.skill)) 

I get this result:

John: score1=25.000 score2=8.333

Cheers,

Steve

like image 262
user8891420 Avatar asked Nov 06 '17 00:11

user8891420


1 Answers

If I understand you correctly, you're asking how you can create variables dynamically. Manipulating the globals() dict to create new variables is not a good idea and you should rather use a list or dictionary to store your csv data.

You seem to need a list, so:

  1. Define the list (student_list in the example below).
  2. Open the csv file.
  3. Create a csv.reader.
  4. Iterate over the rows.
  5. Convert the numbers to floats.
  6. Create a Student instance and pass the name and numbers.
  7. Finally append this student instance to the student_list.

So if your csv file looks like that,

name,score1,score2,rank
john,85,21,1
sarah,72,19,2
bob,45,19,3

try the following code:

import csv


class Student:

    def __init__(self, name, score, rank):
        self.name = name
        self.score = score
        self.rank = rank


student_list = []

with open('temp.csv', newline='') as csv_file:
    reader = csv.reader(csv_file)
    next(reader, None)  # Skip the header.
    # Unpack the row directly in the head of the for loop.
    for name, score1, score2, rank in reader:
        # Convert the numbers to floats.
        score1 = float(score1)
        score2 = float(score2)
        rank = float(rank)
        # Now create the Student instance and append it to the list.
        student_list.append(Student(name, (score1, score2), rank))

# Then do something with the student_list.
like image 180
skrx Avatar answered Sep 17 '22 19:09

skrx