martedì 31 gennaio 2012

Python Shapefile to CSV converter


Read the full article at flaviocdc.net

This script exports the data content (tabular data) of a shapefile and the bounding box of every object to csv format


"""
Shapefile export
"""
import shapelib, dbflib, string
 
SHAPEFILE="shpname"
 
shp = shapelib.ShapeFile(SHAPEFILE)
dbf = dbflib.DBFFile(SHAPEFILE)
 
sCount = shp.info()[0]
dCount = dbf.record_count()
 
if sCount <> dCount:
 raise "Error: shape  number %s (%d) differs from  dbf records (%d) " %(SHAPEFILE,sCount,dCount)
 
 
#print l'header!
header = dbf.read_record(0)
#print header.keys()
intestazione = string.join(header.keys(),"|")
intestazione += "|XMIN|YMIN|XMAX|YMAX"
 
print intestazione
 
#read the dbf file 
for i in range (dbf.record_count() ):
 rc = dbf.read_record(i)
 sc = shp.read_object(i)
 row = ""
 for value in rc.values():
  row += "%s|" %(value)
 #print the  extent/envelope
 (min,max) = sc.extents()
 xmin = min[0]
 ymin = min[1]
 xmax = max[0]
 ymax = max[1]
 
 row += "%f|%f|%f|%f" %(xmin,ymin,xmax,ymax)
 print row
 #print "\n"
 

Nessun commento:

Posta un commento