Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I'm trying to programatically 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...

Thanks

share|improve this question
    
Can you share a dummy shape file? –  R.K. Sep 28 '12 at 15:52
    
how do I share it? email? –  vascobnunes Sep 28 '12 at 15:58
    
    
Have fun programming :) –  R.K. Sep 28 '12 at 16:19
add comment

1 Answer

up vote 8 down vote accepted

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
share|improve this answer
    
hmmm, doesn't do it... –  vascobnunes Sep 28 '12 at 15:54
    
Answer updated. –  R.K. Sep 28 '12 at 16:12
    
Cool! Thanks a lot –  vascobnunes Sep 28 '12 at 16:14
    
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
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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