CEP for Latitude and Longitude Python

Asked

Viewed 218 times

1

Hello I would like to run a CSV that contains more than 100 CEP and return to me, in another CSV, Latitude and Longitude.

I already have the basis to transform the zip code. But I’m not able to read a CSV line by line and return latitude and longitude.

import pycep_correios
from geopy.geocoders import Nominatim

endereco = pycep_correios.get_address_from_cep('01001010')

geolocator = Nominatim(user_agent="test_app")
location = geolocator.geocode(endereco['logradouro'] + ", " + endereco['cidade'] + " - " + endereco['bairro'])

print(location.latitude, location.longitude)

Someone can help me?

thank you

1 answer

3

Assuming that your file .csv contains a simple list of ceps. Ex:

cep
01001010
01017000
  1. Make the reading of the file .csv using the method open() from Python, and store the ceps in a list:

    import csv    
    lista_ceps = []   
    with open('ceps.csv') as file:
        next(file)  # Pula o cabeçalho, caso exista
        for row in csv.reader(file):
            lista_ceps.append(row[0])
    
  2. Turn your code to zip conversion into a function:

    import pycep_correios
    from geopy.geocoders import Nominatim
    
    def extrai_lat_long(cep):
        endereco = pycep_correios.get_address_from_cep(cep)
    
        geolocator = Nominatim(user_agent="test_app")
        location = geolocator.geocode(endereco['logradouro'] + ", " + endereco['cidade'] + " - " + endereco['bairro'])
    
        return(location.latitude, location.longitude)
    
  3. Create a new .csv with CEP, latitude and longitude, using the same method open(), but this time with the output file, and with the parameter 'w' to indicate that the operation is written (write):

     with open('ceps_lat_long.csv', 'w') as file:
         cabecalho = ['cep', 'latitude', 'longitude']
         writer = csv.DictWriter(file, fieldnames=cabecalho)
    
         writer.writeheader() # Escreve o cabeçalho
         for cep in lista_ceps:
             latitude, longitude = extrai_lat_long(cep)
             writer.writerow({'cep': cep, 'latitude': latitude, 'longitude': longitude})
    

The archive ceps_lat_long.csv will look like this:

cep,latitude,longitude
01001010,-23.5512564,-46.6338028
01017000,-23.5453334,-46.6206464

I hope that’s clear!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.