6

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...

15

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
  • You're welcome. An upvote would be nice, too ;-) – R.K. Sep 28 '12 at 16:15
  • I have similar project in .net,code is similar as well.In your code you mentioned that after SetField method,should use SetFeature in order to update layer.Unfortunately that doesn't work.Any ideas ? – Myra Feb 6 '13 at 6:37
  • @Myra You might want to ask that on a separate question. Unfortunately, I'm not really familiar with .NET. Hopefully, others can help you. Just post the question :) – R.K. Feb 21 '13 at 15:19
  • Great, wonder why "SetFeature" is mentioned nowhere in the docs... – adamczi Jul 11 '18 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.