Home Programming Parsing CSV Files in Python

Parsing CSV Files in Python

by Jack Simpson

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.

You may also like