I have been importing a csv dataset containing multiple addresses. I want to get the latitude and longitude of these places and write those to a new csv file along with the original address. I have been trying to use Geopy from python to achieve this. Given below is the code:
import csv
##from time import sleep
from geopy.geocoders import Nominatim
with open('D:/location_to_lat_lon/tolocate.csv', 'r') as fp:
with open('D:/location_to_lat_lon/places_located.csv', 'w',newline='') as op:
a = csv.writer(op)
a.writerow(["Town","District","State","Country","Address","Latitude","Longitude"])
for line in fp.readlines():
geolocator = Nominatim()
town_new = line.split(',')[0]
district_new = line.split(',')[1]
state_new = line.split(',')[2]
country_new = line.split(',')[3]
address_new = line.split(',')[4]
location = geolocator.geocode(address_new)
lat=location.latitude
lon=location.longitude
##time.sleep(3)
a.writerow([town_new,district_new,state_new,country_new,address_new,lat,lon])
However, every time I run this code I get the following error
Traceback (most recent call last): File "", line 13, in lat=location.latitude AttributeError: 'NoneType' object has no attribute 'latitude
Can anyone please help me to resolve this?
'
You are forgetting that location can be None at times due to various reasons including the geocoding service not having geo spatial data for the given address.
simpley do
location = geolocator.geocode(address_new)
if location:
lat=location.latitude
lon=location.longitude
else :
lat = None
long = None
you could do try, except
as well