[gdal-dev] Adding field to Shapefile via Python

Mike Toews mwtoews at gmail.com
Sun Mar 20 18:47:44 EDT 2011


Ok, I found the issue. Rather than adding a new field def'n:
layer_defn.AddFieldDefn(new_field)

it needs to instead be created on the layer:
layer.CreateField(new_field)

The documentation is misleading, as I thought I couldn't add a field
to an existing shapefile if there were features in it. I would
recommend adding a "See also" link from AddFieldDefn to:
http://www.gdal.org/ogr/ogr__api_8h.html#ab585ef1166c61c4819f7fd46ee4a275

-Mike

On 18 March 2011 18:45, Chaitanya kumar CH <chaitanya.ch at gmail.com> wrote:
>
> Mike,
>
> A new field cannot be added to a feature definition while there are any features based on that feature definition.
> See the docs for OGRFeatureDefn::AddFieldDefn()
> http://www.gdal.org/ogr/classOGRFeatureDefn.html#40e681d8464b42f1a1fac655f16ac3dd
>
> On Fri, Mar 18, 2011 at 11:01 AM, Mike Toews <mwtoews at gmail.com> wrote:
>>
>> In a Python script, I am updating an exiting shapefile with data by
>> adding a column. However, my changes don't seem to be saved. Here is
>> what I have:
>>
>> from osgeo import ogr
>> obs_file = 'myfile.shp'
>>
>> source = ogr.Open(obs_file, 1)
>> layer = source.GetLayer()
>> layer_defn = layer.GetLayerDefn()
>>
>> new_field = ogr.FieldDefn('MYFLD', ogr.OFTInteger)
>> layer_defn.AddFieldDefn(new_field)
>>
>> source = None
>>
>> However, when I check the resulting file, I do not see the new field.
>>
>> I have also tried inserting the following (before "source=None")
>>
>> feature = layer.GetNextFeature()
>> feature.GetField('EXIST') # an existing float field with data
>> feature.SetField('EXIST', 111.1) # works
>> feature.SetField('MYFLD', 123) # does nothing
>> layer.SetFeature(feature)
>>
>> Which successfully updates the data in the existing field, but not the
>> added field.
>>
>> Where did I go wrong? Thanks in advance.
>>
>> -Mike
>> _______________________________________________
>> gdal-dev mailing list
>> gdal-dev at lists.osgeo.org
>> http://lists.osgeo.org/mailman/listinfo/gdal-dev
>
>
>
> --
> Best regards,
> Chaitanya kumar CH.
> /tʃaɪθənjə/ /kʊmɑr/
> +91-9494447584
> 17.2416N 80.1426E


More information about the gdal-dev mailing list