Eae
Eae

Reputation: 4321

Geopy exception handling

Traceback (most recent call last):
File "C:\Users\Penguin\workspace\geocode-nojansdatabase\src\geocode.py", line 15, in
place, (lat, lng) = g.geocode(a)
File "C:\Python27\lib\site-packages\geopy-0.94.2-py2.7.egg\geopy\geocoders\google.py", line 81, in geocode
return self.geocode_url(url, exactly_one)
File "C:\Python27\lib\site-packages\geopy-0.94.2-py2.7.egg\geopy\geocoders\google.py", line 88, in geocode_url
return dispatch(page, exactly_one)
File "C:\Python27\lib\site-packages\geopy-0.94.2-py2.7.egg\geopy\geocoders\google.py", line 111, in parse_xml
"(Found %d.)" % len(places))
ValueError: Didn't find exactly one placemark! (Found 3.)

When geopy encounters an address that it does not like my application terminates. What I am wondering is how I can capture the exception in Python and allow my program to move on to the next entry. The source code is below:

import csv
from geopy import geocoders
import time

g = geocoders.Google()

spamReader = csv.reader(open('locations.csv', 'rb'), delimiter='\t', quotechar='|')

f = open("output.txt",'w')

for row in spamReader:
     a = ', '.join(row)
     #exactly_one = False
     time.sleep(1)
     place, (lat, lng) = g.geocode(a)
     b = "\"" + str(place) + "\"" + "," + str(lat) + "," + str(lng) + "\n"
     print b
     f.write(b)

Upvotes: 1

Views: 2470

Answers (1)

weronika
weronika

Reputation: 2639

To make your program ignore the ValueError instead of terminating on it, catch the exception, by replacing:

 place, (lat, lng) = g.geocode(a)

with:

 try:
     place, (lat, lng) = g.geocode(a)
 except ValueError:
     continue

(the continue makes it go to the next repeat of the for loop, instead of trying to execute the rest of the current loop - that seems like the right thing to do, since the rest of the current loop depends on place, lat, lng).

Or, if you want it to print a message, use

 try:
     place, (lat, lng) = g.geocode(a)
 except ValueError as error_message:
     print("Error: geocode failed on input %s with message %s"%(a, error_message))
     continue

Or something along those lines.

Upvotes: 3

Related Questions