#!/usr/bin/python
# -*- coding: UTF-8 -*-

# This script is used to process Penny Harvest data on schools & organisations
# Uses mapq (https://pypi.python.org/pypi/mapq) to access Mapquest API
# More info on Mapquest API: http://open.mapquestapi.com/geocoding/

# Todo, ignore first row, which contains headers

import csv
import sys
import mapq

file_out = sys.argv[1] 
file_in = sys.argv[2]

# Mapquest API key
mapq.key('Fmjtd%7Cluur290y2h%2Cr5%3Do5-90zl54')

# Open the CSV file we're going to write
f = open(file_out, 'a')

# Write the header
f.write('id,lat,lng\n')

# This function loops over all the rows in the file and fetches the coordinates
# for the specified address from Mapquest.
# i = column containing unique ID
# a = address (street) column
# c = city column
# s = state column
# z = zip column
def geocode(id,a,c,s,z):
	with open(file_in, 'rb') as ifile:
		reader = csv.reader(ifile)
		i = 0
		print 'Starting to fetch the coordinates...'
		for row in reader:
			address = (row[a] + ',' + row[c] + ',' + row[s] + ',' + row[z])
			
			#mapq.latlng returns lat lng in a dict
			latlng = mapq.latlng(address)
			lat = latlng.get('lat','-')
			lng = latlng.get('lng','-')
			f.write(row[id] + ',' + str(lat) + ',' + str(lng) + '\n')
			i += 1
			if (i%10) == 0:
				print (str(i) + ' locations fetched...')

if file_in == 'SCHOOLS.csv': 
	geocode(1,35,36,37,38)
elif file_in == 'ORGS.csv':
	geocode(0,2,3,4,5)

# Done. Close the file.
f.close()
@@ -459,118 +459,8 @@
 ')%0A%0A
-# Open the CSV file we're going to write%0Af = open(file_out, 'a')%0A%0A# Write the header%0Af.write('id,lat,lng%5Cn')%0A%0A
 # Th
@@ -535,16 +535,16 @@
 dinates%0A
+
 # for th
@@ -580,17 +580,19 @@
 uest.%0A# 
-i
+uid
  = colum
@@ -796,16 +796,17 @@
 %09%09i = 0%0A
+%0A
 %09%09print 
@@ -844,16 +844,19 @@
 tes...'%0A
+%09%09%0A
 %09%09for ro
@@ -1091,16 +1091,17 @@
 ite(row%5B
+u
 id%5D + ',
@@ -1213,16 +1213,280 @@
 d...')%0A%0A
+# Open the CSV file we're going to write%0Af = open(file_out, 'a')%0A%0A# Write the header%0Af.write('id,lat,lng%5Cn')%0A%0A# Check where the ID and Address columns are located in the csv%0Awith open(file_in, 'rb') as ifile:%0A%09reader = csv.reader(ifile)%0A%09header = list(reader)%5B0%5D%0A%09
 if file_
@@ -1509,34 +1509,44 @@
 sv':
- 
 %0A%09
-geocode(1,35,36,37,38
+%09uid = header.index(%22School ID%22
 )%0A
+%09
 elif
@@ -1574,27 +1574,169 @@
 ':%0A%09
-geocode(0,2,3,4,5)%0A
+%09uid = header.index(%22ORG ID%22)%0A%09a = header.index(%22Address%22)%0A%09c = header.index(%22City%22)%0A%09s = header.index(%22State%22)%0A%09z = header.index(%22Zip%22)%0A%0Ageocode(uid,a,c,s,z)%0A%09%09
 %0A# D

Make geocode script more flexible