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

3

1 Answer 1

14

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
4
  • You're welcome. An upvote would be nice, too ;-)
    – R.K.
    Commented Sep 28, 2012 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
    Commented Feb 6, 2013 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.
    Commented Feb 21, 2013 at 15:19
  • Great, wonder why "SetFeature" is mentioned nowhere in the docs...
    – adamczi
    Commented Jul 11, 2018 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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