Skip to content

Instantly share code, notes, and snippets.

@luciovilla
Last active July 12, 2016 20:39
Show Gist options
  • Save luciovilla/6a1c35d2761669945b53aa794bbad62d to your computer and use it in GitHub Desktop.
Save luciovilla/6a1c35d2761669945b53aa794bbad62d to your computer and use it in GitHub Desktop.
import csv
import time
from pygeocoder import Geocoder
from pygeocoder import GeocoderError
# We can only geocode up to 2500 properties a day (per IP Address)
input_file = open('data.csv', 'r') # Opens the .csv file
output_file = open('data_new.csv', 'w') # Make an empty .csv This is where your geocodes will end up.
data = csv.reader(input_file)
print('begin')
for line in data:
[Address] = line # Make sure the number of columns matches/aligns with the number of fields listed here.
if Address == "Address": # This skips the header. Don't geocode the header :D
Latitude = ["Latitude"]
Longitude = ["Longitude"]
new_line = line + Latitude + Longitude # This adds two new columns to your .csv, Latitude and Longitude.
csv.writer(output_file).writerow(new_line)
print new_line # This isn't required. I just like to watch.
else:
results = Geocoder.geocode(Address)
Latitude = [results.coordinates[0]]
Longitude = [results.coordinates[1]]
new_line = line + Latitude + Longitude
csv.writer(output_file).writerow(new_line)
time.sleep(.21) #This throttles your requests. The GoogleAPI doesn't like too many requests per second.
print new_line
print ('Listo!')
input_file.close()
output_file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment