-2

When I run this code attached to CSV with URL placed at columnA[1] and inserting the names at A[2] getting the following error:

IndexError: List Index out of range

The goal is to extract the location by giving names in CSV format.

# importing the requests library
import requests
import csv

# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"

f = open("z1.csv")
reader = csv.DictReader(f)

for row in reader:
    print(row["URL"])

# location given here
location = row["URL"]

records = location.splitlines()
myreader = csv.reader(records)

for row in myreader:
    print('Location', row[0])

# Defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}

# Sending get request and saving the response as response object
r = requests.get(url = URL, params = PARAMS)

# Extracting data in json format
data = r.json()


# Extracting latitude, longitude and formatted address 
# of the first matching location
latitude = data['results'][0]['geometry']['location']['lat']
longitude = data['results'][0]['geometry']['location']['lng']
formatted_address = data['results'][0]['formatted_address']

# Printing the output
print("Latitude:%s\nLongitude:%s\nFormatted Address:%s"
%(latitude, longitude,formatted_address))
saloua
  • 2,433
  • 4
  • 27
  • 37
  • 3
    Please include the full traceback – roganjosh Jan 13 '18 at 11:38
  • 3
    Also, your indentation is broken. – Georgy Jan 13 '18 at 11:39
  • 1
    Are we supposed to guess, what `z1.csv` contains? Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and edit your question. – Mr. T Jan 13 '18 at 11:53
  • Traceback (most recent call last): File "location.py", line 35, in latitude = data['results'][0]['geometry']['location']['lat'] IndexError: list index out of range – kasheesh kashi Jan 13 '18 at 12:24

1 Answers1

0

You have to make sure that the list data['results'] is not empty before accessing its first element. If it is an empty array then it will raise the exception IndexError : List index Out of range

One more advice, you need to make sure that the field results exists in the dictionary data. Otherwise the call to data["results"] will raise a KeyError exception. Which was not the case in your test. But it is in general a good practice to use the get function instead of the brackets dict.get(key) instead of dict[key].

The fix for your code is:

# importing the requests library
import requests
import csv

# api-endpoint
URL = "http://maps.googleapis.com/maps/api/geocode/json"

f = open("z1.csv")
reader = csv.DictReader(f)

for row in reader:
    print(row["URL"])

# location given here
location = row["URL"]

records = location.splitlines()
myreader = csv.reader(records)

for row in myreader:
    print('Location', row[0])

# Defining a params dict for the parameters to be sent to the API
PARAMS = {'address':location}

# Sending get request and saving the response as response object
# Make sure that you had a successful request
r = requests.get(url = URL, params = PARAMS)
if r.status_code == 200:
    # Extracting data in json format
    data = r.json()


    if data.get("results", []):
        # Extracting latitude, longitude and formatted address 
        # of the first matching location
        latitude = data['results'][0]['geometry']['location']['lat']
        longitude = data['results'][0]['geometry']['location']['lng']
        formatted_address = data['results'][0]['formatted_address']

        # Printing the output
        print("Latitude:%s\nLongitude:%s\nFormatted Address:%s"
        %(latitude, longitude,formatted_address))
saloua
  • 2,433
  • 4
  • 27
  • 37
  • May I know why this corrected code is not showing all locations of all names present in the column A of CSV, but it is only showing the last element's location??? – kasheesh kashi Jan 16 '18 at 11:38
  • As in your original code. This is just showing the first element in the results. `formatted_address = data['results'][0]['formatted_address']` If you want to print all results you should simply add a for loop to iterate over the results. – saloua Jan 18 '18 at 07:48