Reading CSV files in Python


Reading CSV files using Python 3 is what you will learn in this article. The file data contains comma separated values (csv). The comma is known as the delimiter, it may be another character such as a semicolon.

An example csv file:

01/01/2016, 4
02/01/2016, 2
03/01/2016, 10
04/01/2016, 8

The process will be:

read csv file
Read csv file (first step is optional)

Read CSV file

The most basic method to read a csv file is:

import csv
 
with open('file.csv') as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for row in csvReader:
        print(row)

We import the csv module. We read every row in the file. Every row is returned as an array and can be accessed as such, to print the first cells we could simply write:

print(row[0])

We would want to have the data in arrays, we can achieve that using:

import csv
 
dates = []
scores = []
 
with open('file.csv') as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for row in csvReader:
        dates.append(row[0])
        scores.append(row[1])
 
print(dates)
print(scores)

We creates two arrays: dates and scores. We use the append method to add the cells to the arrays.

If you want to use a different delimiter simply change the reader call:

csvReader = csv.reader(delimiter=';')

Load CSV function

If you have many files in an identical format, you can create a function for loading the data:

import csv
 
def readMyFile(filename):
    dates = []
    scores = []
 
    with open(filename) as csvDataFile:
        csvReader = csv.reader(csvDataFile)
        for row in csvReader:
            dates.append(row[0])
            scores.append(row[1])
 
    return dates, scores
 
 
dates,scores = readMyFile('file.csv')
 
print(dates)
print(scores)

Given a filename, the function will read and parse the csv data. Its added to the arrays dates and scores and returned.