Data machine: Reader

Summary

A function to read a comma-separated values (CSV) file into a data set.

Situation

You have data in a comma-separated values (CSV) file you want to read into memory for analysis.

Action

Use the read_csv_data_set function. Call it like this:

  • episodes = read_csv_data_set('episodes.csv')

episodes will be a list of dictionaries.

The function:

  1. import csv
  2.  
  3. def read_csv_data_set(file_name):
  4.     '''
  5.     Read a data set from a CSV file.
  6.  
  7.     Parameters
  8.     ----------
  9.     file_name : string
  10.         Name of the CSV file in the current folder.
  11.  
  12.     Returns
  13.     -------
  14.     data_set : List of dictionaries.
  15.         Data set.
  16.  
  17.     '''
  18.     # Create a list to be the return value.
  19.     data_set = []
  20.     with open('./' + file_name) as file:
  21.         file_csv = csv.DictReader(file)
  22.         # Put each row into the return list.
  23.         for row in file_csv:
  24.             data_set.append(row)
  25.     return data_set

The ./ thing in line 20 means the data file should be in the same folder as the program.

Where referenced