12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- import io
- import requests
- import os.path
- import time
- import shutil
-
- print "Going to delete all contents of geocoded-cities.txt and creating a backup named 'geocoded-cities_back.txt'"
- time.sleep(2) # little delay for reading
-
- # check if file exists, if yes copy to backup and empty it
- if os.path.isfile('geocoded-cities.txt')==True:
- shutil.copy2('geocoded-cities.txt', 'geocoded-cities_back.txt')
- with open('geocoded-cities.txt', 'w+') as ft:
- ft.truncate()
- ft.close()
-
- # empty logfile
- with open('geocode.log', 'w+') as fl:
- fl.truncate()
- fl.close()
-
- with open('cities.txt') as fp:
- for city in fp:
- try:
- payload = {'format': 'json', 'q': ' '}
- payload['q'] = city
- r = requests.get('http://open.mapquestapi.com/nominatim/v1/search', params=payload)
- placesjson = {}
- placesjson = r.json()
- firstResult = placesjson[0] # nominatim delivers (depending on input) multiple resultsets, first one should be the desired
- with open('geocoded-cities.txt', 'aw+') as fgeo:
- fgeo.write("%s, %s, %s\n" % (city.rstrip(), firstResult['lat'], firstResult['lon']))
- print "Status [OK]: %s, %s, %s" % (city.rstrip(), firstResult['lat'], firstResult['lon'])
- with open('geocode.log', 'aw+') as flog:
- flog.write("Status [OK]: %s, %s, %s\n" % (city.rstrip(), firstResult['lat'], firstResult['lon']))
- except:
- print "Status[Not Found]: %s" % city.rstrip()
- with open('geocode.log', 'aw+') as flog:
- flog.write("Status [Not Found]: %s\n" % city.rstrip())
-
- fgeo.close()
- fp.close()
- flog.close()
|