uTrack data to KML: parsing GPS data in Python

uTrack lets you download your vehicle GPS data as a CSV file. However, the CSV doesn’t include nicely-formatted lat/lon columns – instead, you get a fifth row with an address and latlon pair:

Monduli,  (36.9005,-2.9013)

My first attempt at a real Python script took me into regex, reading command line arguments, and basic CSV parsing, all of which took me about twelve times longer than they should have.

If you have Python installed, this script (save as uTrackCSV2KML.py or similar) will parse the file and save a KML file in the same directory. Usage:

python uTrackCSV2KML.py VehicleHistory_AAA123_20121001.csv

### Read uTrack report file into KML
# Load csv, system and getopt libraries
import csv, sys, getopt, re

## Read the file
fname = sys.argv[1]
with open(fname, 'rU') as csvfile:
data = csv.reader(csvfile)
#Skip the 1st header row.
data.next()
data.next()

## Create the KML file
f = open(fname[:-3] + 'kml', 'w')
# Writing the kml file.
'''
The following lines create the headers for a KML file, and set up a style called 'msn_placemark_circle' which will be used for all the points.
'''

f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n")
f.write("<Document>\n")
f.write(" <name>" + fname + '.kml' +"</name>\n")
f.write('<StyleMap id="msn_placemark_circle"><Pair><key>normal</key><styleUrl>#sn_placemark_circle</styleUrl></Pair><Pair><key>highlight</key><styleUrl>#sh_placemark_circle_highlight</styleUrl></Pair></StyleMap><Style id="sh_placemark_circle_highlight"><IconStyle><color>ff0000ff</color><scale>0.590909</scale><Icon><href>http://maps.google.com/mapfiles/kml/shapes/placemark_circle_highlight.png</href></Icon></IconStyle><ListStyle></ListStyle></Style><Style id="sn_placemark_circle"><IconStyle><color>ff0000ff</color><scale>0.5</scale><Icon><href>http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png</href></Icon></IconStyle><ListStyle></ListStyle></Style>')
# Loop through all the rows of the CSV file and create a point for each
for row in data:
f.write(" <Placemark>\n")
# f.write(" <name>" + str(row[0]) + "</name>\n") # best to leave <name> out as it clutters the view in GE
f.write(" <description>" + str(row[0]) + "-" + str(row[1]) + "-" + str(row[2]) + "</description>\n")
f.write(" <styleUrl>#msn_placemark_circle</styleUrl>")
f.write(" <Point>\n")

# Regex to find lat/lon numbers:
p = re.compile('-?[0-9]+.[0-9]+')
m = p.findall(str(row[5]))
lat = m[1]
lon = m[0]

# Write that pair as coordinates for KML:
f.write(" <coordinates>" + lon + "," + lat + "," + str(0) + "</coordinates>\n")
f.write(" </Point>\n")
f.write(" </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
f.close()