[GIS] Converting shapefile to CSV including attributes and geometry

csvexcelgeometrypolygonshapefile

I have a shapefile with 60k+ entries, all of which are polygons with corresponding attributes (acreage totals, landowner names, tax ID #s, etc.). What I ultimately need is a CSV file with all of these attributes and their corresponding geometry (in the KML compatible xyz format, that is, NOT the WKT format).

I know that I can open the .dbf file in Excel and get the attributes. I also know that I can open the shapefile in QGIS and copy the data into Excel, which gets me attributes and WKT geometry.

Is there a simple way to convert the shapefile to CSV (openable in Excel) with attribute and Google Earth friendly geometry?

Best Answer

Here's a simple script that uses the OGR python bindings:

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: and another script to convert from your CSV to 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
Related Question