Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making objects from a CSV file Python [closed]

I'm attempting to create a collection of objects in Python who's properties come from a CSV file.

Currently, I have a simple class:

class myClass:
    name = ""
    age = 0
    hobbies = []

    def __init__(self, var1, var2, var3)
        self.name = var1
        self.age = var2
        self.hobbies = var3

In an effort to store a lot of data without cluttering the code, I've created a CSV file like so:

Robert Samson,50,swimming,biking,running
Sam Robertson,70,reading,singing,swimming

and so on. I should have about 50 of these, and they may change, which is my reasoning for using CSV.

Is there a way to systematically make myClass objects from this CSV file? I've read you shouldn't try and make objects with unique names in a loop but I'm not sure why.

Thanks

EDIT: I'm not looking for a way to store the csv data in python, I need to create objects... my example code is a little misleading in that myClass has functions that I'd like to be able to call

like image 476
ChuckDavis Avatar asked Jul 08 '14 21:07

ChuckDavis


People also ask

How do you close a csv file in Python?

Close a CSV FileUse the close() function to close an open file.

How do I read and print a csv file in Python?

csv file in reading mode using open() function. Then, the csv. reader() is used to read the file, which returns an iterable reader object. The reader object is then iterated using a for loop to print the contents of each row.


2 Answers

Just create an empty list and add the objects to it:

import csv

my_list = []

with open('file.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        my_list.append(myClass(row[0], row[1], row[2:]))
like image 186
user3557327 Avatar answered Oct 20 '22 14:10

user3557327


Why not just use a dictionary?

import csv

persons = []

with open('file.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        persons.append({'name': row[0], 'age': int(row[1]), 
                        'hobbies': row[2:]})
like image 24
Roland Smith Avatar answered Oct 20 '22 13:10

Roland Smith