Search code examples
pythonloopsexceptiongeocode

list iterating exception so the loop keeps going, geocode


I have a list of place names and I want to iterate over it to get the coordinates:

import time
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="xxx")
for a in pl:
    location = geolocator.geocode(a)
    print(location.latitude)
    time.sleep(2)

Now it works for the first few entries, then I get the following error:

AttributeError: 'NoneType' object has no attribute 'latitude'

I assume that that particular entry is not in a format that can be interpreted. How can I make my loop go on in those cases and just leave the entry black for these one, or just delete the entry outright.


Solution

  • You can check if location is not None, and then only get the latitude attribute from it

    import time
    from geopy.geocoders import Nominatim
    geolocator = Nominatim(user_agent="xxx")
    for a in pl:
        location = geolocator.geocode(a)
        #If location is not None, print latitude
        if location:
            print(location.latitude)
        time.sleep(2)