0

I know how to use geopy to convert a single address to GPS coordinates, but am having trouble with my code which should read addresses line by line from a file and convert each one to GPS coordinates and print them out.

from geopy.geocoders import Nominatim
geolocator = Nominatim()

f = open("FILE PATH")
line = f.readline()

for line in f.readlines():
    address = line
    location = geolocator.geocode(address)
    print((location.latitude, location.longitude))
f.close()
Harrison
  • 5,095
  • 7
  • 40
  • 60
  • What exactly is the issue? – Kendas Jun 14 '16 at 13:58
  • http://imgur.com/LIIbg4m That's what the console is giving me. – Harrison Jun 14 '16 at 14:00
  • First, you're assigning the first line of `f` to the variable `line` and basically dismissing the value by reading the rest of the file. Second, the file handler `f` can be iterated over on itself like `for address in f:`. Third, does the code produce any results prior to the error? – Kendas Jun 14 '16 at 14:04
  • It doesn't produce anything. How should I go about fixing it? This is now what I currently have: http://imgur.com/QHt7v5v – Harrison Jun 14 '16 at 14:07
  • Try the answer on this question: http://stackoverflow.com/questions/27914648/geopy-catch-timeout-error – Kendas Jun 14 '16 at 14:13
  • This is my code now: http://imgur.com/5F775v7 However, now it's just printing "Timed Out" for every address in the file – Harrison Jun 14 '16 at 14:18
  • Do these addresses work individually or directly from the interpreter? The format may be off. It seems that the timeout is the reaction geopy has to addresses it can't resolve. – Kendas Jun 14 '16 at 14:25
  • I tried the default address from the geopy documentation on the github page and even that address timed out. – Harrison Jun 14 '16 at 14:29

1 Answers1

2

This worked for me.

from geopy import Nominatim
import time


geolocator = Nominatim()

with open("addresses",'r') as fp:
    for line in fp:
        location = geolocator.geocode(line)
        # print (location.latitude, location.longitude)
        time.sleep(1)
shaddyshad
  • 217
  • 4
  • 15
  • 2
    If you're going to do something like this, note that Nominatim's usage policy only allows a maximum of 1 request per second (unless you are using your own Nominatim instance): https://operations.osmfoundation.org/policies/nominatim/. You could add a `time.sleep(1)` in the `for` loop to stay within that requirement. – salsbury Jun 08 '19 at 15:51