J Freake J Freake - 1 year ago 76
Python Question

How do I import a CSV into an have each line be an object?

I have a csv file with 8-12 values per line, this is spending data with categories, payment method, date, amount etc. Each line is a single purchase with these details. I want to import the file into python into a list that I can then iterate through easily to find for example, how much was spent on a given category in a given month. Is there a good method to create an object for a single purchase that has all of the attributes that I want and then do an import from a csv into a list of these objects?

Answer Source

One tricky/hacky thing you can do with objects is programatically create them with dict. Here is an example:

In [1]: vals = {"one":1, "two":2}
In [2]: class Csv():pass

In [3]: c = Csv()

In [4]: c.__dict__ = vals

In [5]: c.one
Out[5]: 1

So, yes, you could create an empty object, create a dict, then insert it into the empty object so you can use it like an object with set attributes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download