How do I import a CSV into an individual line?

advertisements

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?


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.