Steffen Steffen - 5 months ago 25
Python Question

Reverse geocode, reading .CSV file and TypeError: a float is required

Fixed: Added float() to coordinates1 and coordinates2:

my_location = gmaps.reverse_geocode(float(coordinates1), float(coordinates2))


I'm trying to convert lat long coordinates to addresses. I have a .CSV file with the coordinates, and I don't know if my code can read it, or if it's something else that's wrong.
Here is my code:

from pygeocoder import Geocoder
import csv

gmaps = Geocoder(api_key='api-key')

input = open('C:/Users/Steffen/PycharmProjects/untitled/sadist.csv','r')
output = open('C:/Users/Steffen/PycharmProjects/untitled/distsaretailer.csv', 'w')

try:
reader = csv.reader(input)
writer = csv.writer(output)

for row in reader:
print(row)
coordinates1 = row[0]
coordinates2 = row[1]

my_location = gmaps.reverse_geocode(coordinates1,coordinates2)

writer.writerow(my_location)

finally:
input.close()
output.close()


The error message:

Traceback (most recent call last):
File "C:/../latlongs.py", line 22, in <module>
my_location = gmaps.reverse_geocode(coordinates1,coordinates2)

File "C:\..\pygeocoder.py", line 155, in reverse_geocode
'latlng': "%f,%f" % (lat, lng),
['69.9687376', '23.2715496']
TypeError: a float is required

Answer

As PM 2Ring pointed out, you need to convert the coordinates from strings into floating point numbers. Replace:

coordinates1 = row[0]
coordinates2 = row[1]

with:

coordinates1, coordinates2 = [float(c) for c in row]
Comments