I have a script that takes addresses from a CSV, and tries to find the GPS coordinates.
I am still learning Python, so comments as to general formatting (i.e. variable names, function names, etc.) are appreciated, as well as ways to tighten up the code. (I'm using the csv module and geopy).
The CSV is a single column of addresses (following are dummy addresses) saved as a
123 Main Street, Chicago, IL 12345 3214 Overland Drive, Los Angeles, CA 49382 29 NE 9th Street, New York, NY 29384
And my .py file:
import csv from geopy.geocoders import Nominatim from geopy.geocoders import GoogleV3 ADDRESS_FILE = "Addresses" def read_csv(file): with open(file,'r') as f: reader = csv.reader(f) address_list = list(reader) return address_list def get_lat_lon(address): geolocator = Nominatim() try: location = geolocator.geocode(address) return location.latitude, location.longitude except Exception: return 0, 0 def google_lat_lon(address): geolocator = GoogleV3(api_key="xxxxx") try: location = geolocator.geocode(address) return location.latitude, location.longitude except Exception: return 0, 0 def find_coordinates(address): google_found = "" lat, lon = get_lat_lon(address) lat, lon = google_lat_lon(address) if lat == 0 and lon == 0: lat, lon = google_lat_lon(address) google_found = "Note: used Google" return lat, lon, google_found def write_file(info): with open(ADDRESS_FILE+" with GPS.csv","w", newline='') as csvfile: writer = csv.writer(csvfile, delimiter = ",") for line in info: writer.writerow(line) def main(): addresses = read_csv(ADDRESS_FILE+".csv") address_GPS =  for address in addresses: addr = address.replace(u'\xa0', u' ') lat, lon, google_found = find_coordinates(addr) address_GPS.append((addr,lat,lon, google_found, '=HYPERLINK("https://www.google.com/maps/search/"&B1&","&C1,"Link")')) for addr in address_GPS: print(addr[:len(addr)-1]) write_file(address_GPS) if __name__ == '__main__': main()
addr = address.replace(u'\xa0', u' ')- I have this because for some reason when reading the CSV,
\xa0appears in the string, throwing off the lookup. I think it's due to Encoding? I created the CSV in Excel, File-> Save as .CSV (regular
.csv, not the option for Mac, or whatever else).
except Exception:- I think I should be more specific here? That's there in case there's no location found with the address.
if lat == 0 and lon == 0is there in case the regular geopy lookup doesn't work, I use their Google Maps option. But say that doesn't work, and I want to use Bing or edit the address, there's probably a better way than keep on nesting that
if lat == 0 and lon == 0part.
Is it okay to have my
main()like I do? Or is it better to keep the lines in
main()to primarily be function calls?
Is it wise/good practice to have a
return a, b, c, ..., z? Or is it best to return just one or two things per