from opencage.geocoder import OpenCageGeocode import json key = '59713351589a4d55a9fa1b286191d47b' geocoder = OpenCageGeocode(key) towns = [] with open('towns.txt', encoding='utf8') as f: town = f.readline().strip('\n') while town: result = geocoder.geocode(town) if result and len(result): print("writing " + town) longitude = result[0]['geometry']['lng'] latitude = result[0]['geometry']['lat'] towns.append((town, {'lat': latitude, 'lon': longitude})) town = f.readline().strip('\n') with open('lats_lons.txt', 'w+', encoding='utf8') as f: f.write(json.dumps(towns))