Reading A User Specifed Column From Csv
I've written a small script that scans the content of a csv file for a series of location names, and then uses Geolocation API to fetch and display Latitue and Longitude co-ordinat
Solution 1:
One way would be to use a generator expression to extract the desired column from each row of data read from the csv file, and then iterate over that with afor
loop.
A nice thing about this approach is that it could easily be expanded to extract multiple columns from each row if needed. It's also fairly memory efficient because it iteratively processes one row at a time from the file.
import csv
import urllib
import xml.etree.ElementTree as ET
path = raw_input("Enter source filepath: ")
col = int(raw_input("Column # to extract (starting with zero): "))
latlist = []
lnglist = []
try:
withopen(path, 'r+') as filein:
data = csv.reader(filein, skipinitialspace=True)
for item in (row[col] for row in data):
urlpath = (
"http://maps.googleapis.com/maps/api/geocode/xml?address=" +
item + "&sensor=true")
xml = urllib.urlopen(urlpath)
tree = ET.parse(xml)
root = tree.getroot()
for location in root.iter('location'):
lat = location.find('lat').text
latlist.append(lat)
lng = location.find('lng').text
lnglist.append(lng)
print"\n\nLATS\n==========================\n"for lats in latlist:
print lats
print"\n\nLONGS\n==========================\n"for longs in lnglist:
print longs
except Exception as e:
printstr(e)
P.S. Since your exception handler does nothing but print the exception, it might be better to just leave thetry/except
block out because that's what would happen automatically anyway, plus it would print something very useful called a traceback which will show exactly where the problem occurred.
Post a Comment for "Reading A User Specifed Column From Csv"