For reading .csv files, you can use the csv module like this:
reader = csv.reader(open("file.csv"))
for row in reader:
for value in row:
...
You might get in trouble when your file is UTF-8 encoded, since csv
does not support that. But there is a wrapper which will take care of this.
You can, of course, also simply read your file line by line and split it by commas: values=line.split(',')
.
Being that that the kml format is not very complicated, the toughest part of creating a representation of your data is deciding what it should look like. A very simple piece of code to insert the values read from the csv file could look like this:
# read field labels from first line in file
header = reader.next()
# prepare static output
templates = [(' <Placemark>\n <name>{}</name>\n', 'name'),
(' <description>\n <![CDATA[\n <img src="{}"/>\n', 'image'),
(' {}\n', 'address'),
(' {}\n', 'postcode'),
(' {}\n', 'country'),
(' Tel: <span class="tel">{}</span>\n', 'telephone'),
(' Mail: <span class="mail">{}</span>\n', 'Email'),
(' </description>\n <Point>\n <coordinates>{},', 'lat'),
('{}</coordinates>\n </Point>\n </Placemark>\n', 'lng')]
# lookup function for field values. leading and trailing whitespace will be removed
value = lambda field, array: array[header.index(field)].lstrip().rstrip()
# start output
print '''<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>'''
# insert values into xml
for row in reader:
for t, f in templates:
print t.format(value(f, row)),
print ' </Document>\n</kml>'