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:
- import csv
- def read_csv_data_set(file_name):
- '''
- Read a data set from a CSV file.
- Parameters
- ----------
- file_name : string
- Name of the CSV file in the current folder.
- Returns
- -------
- data_set : List of dictionaries.
- Data set.
- '''
- # Create a list to be the return value.
- data_set = []
- with open('./' + file_name) as file:
- file_csv = csv.DictReader(file)
- # Put each row into the return list.
- for row in file_csv:
- data_set.append(row)
- return data_set
The ./
thing in line 20 means the data file should be in the same folder as the program.
Where referenced