18

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

ChuckDavis
  • 219
  • 1
  • 2
  • 8
  • 2
    You should bear [this](http://stackoverflow.com/q/1680528/3001761) in mind. – jonrsharpe Jul 08 '14 at 21:29
  • [this](http://stackoverflow.com/questions/13368498/python-object-as-dictionary-value) might be of interest to you, if you haven't already seen it – ajdigregorio Jul 08 '14 at 21:30
  • just make a `list` of `myClass` objects as you read in the file – cmd Jul 08 '14 at 21:36
  • There is no need to make `name`, `age` and `hobbies` [class variables](https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables). Just initializing them as instance variables in `__init__()` is enough. – Roland Smith Jul 08 '14 at 22:01
  • 1
    You need to read [this](http://stackoverflow.com/questions/447898/what-is-object-serialization). – user2963623 Jul 08 '14 at 22:09

2 Answers2

28

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:]))
user3557327
  • 1,109
  • 13
  • 22
3

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:]})
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • 2
    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 – ChuckDavis Jul 09 '14 at 13:09
  • 1
    Because you might need to merge data, or validate a data model. – ncfx1099 Dec 09 '20 at 21:36