Eae
Eae

Reputation: 4321

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....

Upvotes: 0

Views: 707

Answers (2)

BrenBarn
BrenBarn

Reputation: 251428

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

Upvotes: 1

ChristopheD
ChristopheD

Reputation: 116237

As you can see in the error message, the problem is in the place, (lat, lng) = ... line.

It is the g.geocode calll which returns None (and you try to assign this to the place variable and the lat, lng tuple immediately, which obviously must fail).

So try something along these lines:

result = g.geocode(a)
if result:
    place, (lat, lng) = result
else:
    # ...

Upvotes: 1

Related Questions