Saturday, 26 December 2015

python - Programmatically populating shapefile field with polygon areas in OGR?


I'm trying to programmatically populate a shp field with polygon areas:


import sys
import ogr

ds = ogr.Open( 'tttttttttt.shp', update = 1 )

if ds is None:
print "Open failed./n"
sys.exit( 1 )

lyr = ds.GetLayerByName( "tttttttttt" )
lyr.ResetReading()

field_defn = ogr.FieldDefn( "Area", ogr.OFTReal )
lyr.CreateField(field_defn)


for i in lyr:
# feat = lyr.GetFeature(i)
geom = i.GetGeometryRef()
area = geom.GetArea()
print 'Area =', area
lyr.SetFeature(i)
i.SetField( "Area", area )

ds = None


But I get an empty values in the field...



Answer



You have to use lyr.SetFeature(i) to trigger the update in your shape file. You'll have to close the data sources in the end so things get written.


import sys
import ogr

ds = ogr.Open( 'tttttttttt.shp', update = 1 )
if ds is None:
print "Open failed./n"
sys.exit( 1 )


lyr = ds.GetLayerByName( "tttttttttt" )
lyr.ResetReading()

field_defn = ogr.FieldDefn( "Area", ogr.OFTReal )
lyr.CreateField(field_defn)

for i in lyr:
# feat = lyr.GetFeature(i)
geom = i.GetGeometryRef()

area = geom.GetArea()
print 'Area =', area
lyr.SetFeature(i)
i.SetField( "Area", area )
lyr.SetFeature(i)
ds = None

*Low-rep comment and concern: If the 'Area' field already exists, this code creates an extra field, like "Area_n", and overwrites the existing Area field. Maybe folks should add some safety code like:


ldef = lyr.GetLayerDefn()
if ldef.GetFieldIndex("Area") != -1:

print "'Area' field already defined"
... # exit or overwrite logic

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...