Shapefile – Adding Custom Feature Attributes Using OGR in Python

ogrosgeoshapefile

I am seeking a way to take an existing Shapefile that has a Feature set of 200 countries. Each country Feature has an attribute of "NAME." My objective is to create a Python script that adds an arbitrary (for now) additional attribute, say, "POPULATION".

Of course I have the OSGeo and GeoDjango modules installed. I'm as far as:

 from osgeo import ogr

    infile = ogr.Open('sample.shp', 1) #'sample.shp' is a pre-existing ESRI shapefile described above
    inlyr = ogr.GetLayerByIndex(0)

Am I missing an OGR function that will allow me to insert Feature attribute fields into an existing Shapefile?

Best Answer

Is it possible to add a field to an existing shapefile using Python OGR..

from osgeo import ogr
driver = ogr.GetDriverByName('ESRI Shapefile')
dataSource = driver.Open(“c:/test/Test2.shp”, 1) #1 is read/write

#define floating point field named DistFld and 16-character string field named Name:
fldDef = ogr.FieldDefn('DistFld', ogr.OFTReal)
fldDef2 = ogr.FieldDefn('Name', ogr.OFTString)
fldDef2.SetWidth(16) #16 char string width

#get layer and add the 2 fields:
layer = dataSource.GetLayer()
layer.CreateField(fldDef)
layer.CreateField(fldDef2)