2

I have a csv file that has 1800+ addresses. I need to compare the distance of every single one of them with a specific address. I wrote a code that does that But only if I add the address manually.

I want to run this code on every line of the csv file and print the distance in km and in minutes. How can I do that?

This is my code:

# Needed to read json and to use the endpoint request
import urllib.request
import json

# Google MapsDdirections API endpoint
endpoint = 'https://maps.googleapis.com/maps/api/directions/json?'
api_key = 'add api'

# Give the original work address and lists of addresses.
# Format has to be (Number Street Name City Province)
# So for example 1280 Main Strret Hamilton ON

origin = ('add the one address to calculate distance with the other').replace(' ', '+')
destinations = ['address1', 'address2', 'address3']
distances = []

# Goes through the array of addresses and calculated each of their distances
for i in range(len(destinations)):
    # Replaces the spaces with + so that it can properly work with the google maps api url
    currentDestination = destinations[i].replace(' ', '+')

    # Building the URL for the request
    nav_request = 'origin={}&destination={}&key={}'.format(origin, currentDestination, api_key)

    # Builds the request to be sent
    request = endpoint + nav_request

    # Sends the request and reads the response.
    response = urllib.request.urlopen(request).read()

    # Loads response as JSON
    directions = json.loads(response)

    # Gets the distance from the address in the array to the origin address
    distance = directions["routes"][0]["legs"][0]["distance"]["text"]

    # Adds it to the list of distances found from each address
    distances.append(distance)

#print distances
print(*distances, sep="\n")

instead of having a list destinations, it should loop through the csv file addresses

Chadi N
  • 439
  • 3
  • 13

1 Answers1

1

Considering that your file has just one column with addresses and no quotes and begin/end then task is simply reading lines from file into list. This can be done following way

with open("addresses.txt","r") as f:
    addresses = [i.rstrip("\n") for i in f]
print(addresses[:20])  # this will show at most 20 entries, which should allow check if it works as intended

Please run following code after replacing addresses.txt with name of your file and write if it work as intended. with open... is used to more that file is closed properly after it was used, .rstrip is used to remove newlines from ends of lines.

Daweo
  • 31,313
  • 3
  • 12
  • 25
  • Thanks for the reply, but it only print the actual addresses when i run your code – Chadi N Nov 03 '21 at 15:39
  • 1
    @MelanieDeschene, this is what it should do, please add my code brefore your code and then replace `destinations = ['address1', 'address2', 'address3']` using `destinations = addresses` and then it should work – Daweo Nov 03 '21 at 15:49
  • it's working perfectly. But I would like to ask you one last thing. Is it possible to print "error" when it run an address that is not working properly? so it doesnt crash the code and keep running for the next addresses – Chadi N Nov 03 '21 at 16:01
  • @MelanieDeschene search for `python`'s try-except – Daweo Nov 03 '21 at 18:55