[OSGeo-Discuss] methods for programatically adding fields to shapefiles
Tyler Erickson
tyler.erickson at mtu.edu
Fri Oct 31 10:18:26 PDT 2008
Thanks for all the suggestions. Although it is still a work in progress,
it's looking like the ogr library approach suggested by David will work out
for me...
- Tyler
def create_formatted_shapefile_using_ogr(infile, outfile):
# setup a spatial reference
srs_out = osr.SpatialReference()
srs_out.SetFromUserInput('WGS84')
ogrdriver = ogr.GetDriverByName('ESRI Shapefile')
dsInput = ogrdriver.Open(infile)
mLayer = dsInput.GetLayer()
featureCount = mLayer.GetFeatureCount()
# create the output shapefile
if os.path.exists(outfile):
ogrdriver.DeleteDataSource(outfile)
dsOutput = ogrdriver.CreateDataSource(outfile)
outLayer = dsOutput.CreateLayer(dsOutput.GetName(), \
geom_type = ogr.wkbPolygon, \
srs = srs_out)
outLayer.CreateField(ogr.FieldDefn('start_date', ogr.OFTDate))
outLayer.CreateField(ogr.FieldDefn('fire_code', ogr.OFTString))
outLayer.CreateField(ogr.FieldDefn('fire_name', ogr.OFTString))
outLayer.CreateField(ogr.FieldDefn('source', ogr.OFTString))
print 'FeatureCount = ' + str(featureCount)
for iFeature in range(0,mLayer.GetFeatureCount()):
inFeature = mLayer.GetFeature(iFeature)
geom = inFeature.GetGeometryRef()
start_date = inFeature.GetFieldAsString('year') + "-" + \
inFeature.GetFieldAsString('startmonth') + "-" + \
inFeature.GetFieldAsString('startday')
# reproject to WGS84
geom.TransformTo(srs_out)
# write the attributes to the output file
outFeature = ogr.Feature(feature_def=outLayer.GetLayerDefn())
outFeature.SetGeometry(geom)
outFeature.SetFID(1)
outFeature.SetField('fire_code', inFeature.GetField('fire_id'))
outFeature.SetField('fire_name', inFeature.GetField('fire_name'))
outFeature.SetField('source', infile)
outLayer.CreateFeature(outFeature)
outFeature.Destroy()
inFeature.Destroy()
dsInput.Destroy()
dsOutput.Destroy()
--
View this message in context: http://n2.nabble.com/methods-for-programatically-adding-fields-to-shapefiles-tp1395535p1437802.html
Sent from the OSGeo Discuss mailing list archive at Nabble.com.
More information about the Discuss
mailing list