Parsing CSV Files in Python

Almost anyone doing research at some point will have to input or extract data from an Excel spreadsheet. However, it is possible to export an Excel file as a .csv file (comma separated file) and then use Python to grab all the data instantly. The Python csv module makes all this incredibly simple:

import csv
column1 = []
column2 = []
column3 = []
openfile = csv.reader(open('data.csv'))
for row in openfile:
    first, second, third = row
    column1.append(first)
    column2.append(second)
    column3.append(third)

This script will open your .csv file, and then use the ‘.next()’ method to create an array of all the lines in your file, which you can parse through with the for loop.

The following two tabs change content below.
Computational biology PhD candidate at the Australian National University. I love writing (both articles and software), learning more about the world around us, and beekeeping. I also write for BioSky.co

Latest posts by Jack Simpson (see all)

Comments are closed.