Search code examples
pythongeopy

GeocoderDotUS... Syntax of Python check for 'None'


import csv
from geopy import geocoders
import time

g = geocoders.GeocoderDotUS()

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)


    if None in (lat, lng):
        f.write("none")
    else:
        b = str(place) + "," + "[" + str(lat) + "," + str(lng) + "]" + "\n"
        print b
        f.write(b)

So I have established that if GeocoderDotUS does not find an address it will return None. I have written some script to attempt to check for None however I still seem to be getting this trace back. I am a bit perplexed.

Traceback (most recent call last):
File "C:\Users\Penguin\workspace\geocode-nojansdatabase\src\GeocoderDotUS.py", line 17, in <module>
place, (lat, lng) = g.geocode(a)
TypeError: 'NoneType' object is not iterable

Is there some error in my check for None systax? Thanks in advance for any help out....


Solution

  • I don't know anything about geopy, but it looks like the problem is just what you said: if geocode doesn't find it, it returns None. Just None, not a tuple with None as the elements. So you need to check for None before you assign the results to lat and lng. Something like:

    geoResult = g.geocode(a)
    if geoResult is None:
        f.write("none")
    
    # If we get here, the result is not None and we can proceed normally
    place, (lat, lng) = geoResult
    b = "..." # continue with your processing here