Berikut ini skrip sederhana yang menggunakan binding python OGR :
import ogr,csv,sys
shpfile=r'C:\Temp\test.shp' #sys.argv[1]
csvfile=r'C:\Temp\test.csv' #sys.argv[2]
#Open files
csvfile=open(csvfile,'wb')
ds=ogr.Open(shpfile)
lyr=ds.GetLayer()
#Get field names
dfn=lyr.GetLayerDefn()
nfields=dfn.GetFieldCount()
fields=[]
for i in range(nfields):
fields.append(dfn.GetFieldDefn(i).GetName())
fields.append('kmlgeometry')
csvwriter = csv.DictWriter(csvfile, fields)
try:csvwriter.writeheader() #python 2.7+
except:csvfile.write(','.join(fields)+'\n')
# Write attributes and kml out to csv
for feat in lyr:
attributes=feat.items()
geom=feat.GetGeometryRef()
attributes['kmlgeometry']=geom.ExportToKML()
csvwriter.writerow(attributes)
#clean up
del csvwriter,lyr,ds
csvfile.close()
EDIT: dan skrip lain untuk dikonversi dari CSV ke KML
import ogr,csv,sys,os
ogr.UseExceptions()
csvfile=r'C:\temp\test.csv' #sys.argv[1]
kmlfile=r'C:\temp\test.kml' #sys.argv[2]
csvreader=csv.reader(open(csvfile,'rb'))
headers=csvreader.next()
ds = ogr.GetDriverByName('KML').CreateDataSource(kmlfile)
lyr = ds.CreateLayer(os.path.splitext(os.path.basename(kmlfile))[0])
for field in headers[:-1]: #skip kmlgeometry
field_def = ogr.FieldDefn(field)
print lyr.CreateField(field_def)
for rec in csvreader:
feat = ogr.Feature(lyr.GetLayerDefn())
for i,field in enumerate(headers[:-1]): #skip kmlgeometry
feat.SetField(field, rec[i])
feat.SetGeometry(ogr.CreateGeometryFromGML(rec[-1]))
lyr.CreateFeature(feat)
del lyr,ds