Reading CSV files in Python

I know the easiest way to get my large table of From and To results passed to Python is to create a comma separated value (.csv) table. Its very easy to edit this, as I can simply open a text editor and start my data entry. Below is an example of how a very simple TO and FROM table would look like in csv:

From,To
Edmonton,Hinton
Vancouver,Burnaby
Edmonton,Calgary

To load and parse through these values in Python I need open the file and then return all the rows. The script do do this is below. Please note that it is very important to store the .csv file in your current working directory instead of some random folder on your hard drive!

import csv
f = open('testtable.csv')
csvf = csv.reader(f)
for row in csvf:
    print(row)

And from running that with the csv above we get the following output, with each row as a separate list of strings:

['From', 'To']
['Edmonton', 'Hinton']
['Vancouver', 'Burnaby']
['Edmonton', 'Calgary']

The next step is to pass each value in this list of strings to the Google Directions API and store the returns in a database!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s