2

i'm having an issue with creating a new field in a layer create on a memory data source and adding values to it : here is my snippet code .

newfield = ogr.FieldDefn("aa", ogr.OFTReal)
erasedlayer.ResetReading()
erasedlayer.CreateField(newfield)
for i in range(erasedlayer.GetLayerDefn().GetFieldCount()):  # iterate on parcelle features to get the names
    print(erasedlayer.GetLayerDefn().GetFieldDefn(i).GetName())
erasedlayer.ResetReading()
for feature in erasedlayer:
    feature.SetField("aa", feature.GetGeometryRef().GetArea())

and this is the error i got :

Traceback (most recent call last):
  File "/home/kail/PycharmProjects/project/file.py", line 190, in <module>
    feature.SetField("aa", feature.GetGeometryRef().GetArea())
  File "/usr/lib/python3/dist-packages/osgeo/ogr.py", line 4808, in SetField
    return _ogr.Feature_SetField(self, *args)
RuntimeError: Invalid field name: 'aa'

i verified with the loop for the field names on my layer and the "aa" field exist

  • I ran your code using an already-open layer I had, and I got no errors. I can see the field "aa" has been properly added. – Jon Oct 20 '17 at 23:05
  • can you put the snippet code you run , cuz for me i check with : for i in range(erasedlayer.GetLayerDefn().GetFieldCount()): # iterate on parcelle features to get the names print(erasedlayer.GetLayerDefn().GetFieldDefn(i).GetName()) and the field is added to the layer but when the program arrive to this point : feature.SetField("aa", feature.GetGeometryRef().GetArea()) it says the errror above – Abdelaziz Oct 23 '17 at 12:20
  • I just copy and pasted your code exactly, then I changed all instances of "erasedlayer" to "layer", since that is what my layer was called. Must be a problem with your erasedlayer. I created my layer with: ds = ogr.Open(shp_path,1) layer = ds.GetLayer() – Jon Oct 23 '17 at 14:55
  • Thanks, I rewrote the code as a function that copy the layer to a new layer, do the rest and return it – Abdelaziz Oct 23 '17 at 15:16

Your Answer

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

Browse other questions tagged or ask your own question.