0

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?

J Freake
  • 3
  • 2

2 Answers2

0

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.

Noah Gift
  • 256
  • 1
  • 4
  • 9
0

Python brings its own CSV reader in the csv module. You can use it to read your CSV file and convert the lines to objects like this:

import csv

# Read values from csv file.

values = []
with open('file.csv', 'r') as csv_file:
    # Replace the delimiter with the one used in your CSV file.
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row_values in csv_reader:
        # If a line in your CSV file looks like this: a,b,c
        # Then row_values looks something like this: ['a', 'b', 'c']
        values.append(row_values)

# Convert the list of lists (which represent the CSV values) to objects.

column_names = ['first_column', 'second_column', 'third_column']
objects = []
for row_values in values:
    objects.append({key: value for key, value in zip(column_names, row_values)})
# objects is now a list of dicts with one dict per line of the CSV file.

# The dicts could e.g. be converted to objects with this:
class MyObject:
    def __init__(self, first_column, second_column, third_column):
        self.first_column = first_column
        self.second_column = second_column
        self.third_column = third_column
print(objects)
objects = [MyObject(**object) for object in objects]
# Alternative:
alternative_objects = []
for object in objects:
    new_object = object()
    new_object.__dict__ = object
    alternative_objects.append(new_object)

Please refer to the Python 2.7 or 3.x documentation for further details on the CSV module.

mxscho
  • 1,990
  • 2
  • 16
  • 27
  • Is this only for python 3? – J Freake Oct 17 '16 at 03:00
  • No. The CSV module is also available for Python 2.7. But my code is tested in Python 3. It actually contains a little error. I'll fix this - gimme a minute. :) – mxscho Oct 17 '16 at 03:01
  • Sorry. :) It should work now. You can find the Python 2.7 documentation here (it should be the same though): https://docs.python.org/2/library/csv.html – mxscho Oct 17 '16 at 03:09