[gdal-dev] Is it possible to add new fields to a shapefile and populate then?

Rutger kassies at gmail.com
Tue Apr 4 04:15:16 PDT 2017


Stephen Woodbridge wrote
> On 4/3/2017 11:37 PM, jratike80 wrote:
>> Stephen Woodbridge wrote
> 
> Hi Jukka,
> 
> Ahh, good point, I always seem to forget that fact.
> I have gotten the python code to add the new fields, but the data is not 
> getting written to the file.
> 
>      # open the shapefile
>      driver = ogr.GetDriverByName('ESRI Shapefile')
>      dataSource = driver.Open(infile, 1) # open for rw
>      if dataSource is None:
>          print "ERROR: could not open '%s' as shapefile!" % (infile)
>          sys.exit(1)
> 
>      layer = dataSource.GetLayer()
>      layer.CreateField(ogr.FieldDefn("area",     ogr.OFTReal))
> 
> 
>      for feature in layer:
>          geom = feature.GetGeometryRef()
>          feature.SetField("area", geom.GetArea())
>          feature = None
> 
>      dataSource = None
> 
> In the cookbook example for "Create a New Shapefile and Add Data" there 
> is a call to:
> 
> layer.CreateFeature(feature)
> 
> but I do not see an equivalent call for:
> 
> layer.UpdateFeature(feature)
> 
> So How do I update the feature and force the data to get written to the 
> shapefile. I'm presuming the CreateFeature will append a new record 
> which is not what I want.
> 
> -Steve
> 
> ---
> This email has been checked for viruses by Avast antivirus software.
> https://www.avast.com/antivirus
> 
> _______________________________________________
> gdal-dev mailing list

> gdal-dev at .osgeo

> https://lists.osgeo.org/mailman/listinfo/gdal-dev

Hey Stephen, 

I think you looking for "layer.SetFeature(feature)", which you can add right
before destroying the changed feature object withing your loop.


Regards,
Rutger




--
View this message in context: http://osgeo-org.1560.x6.nabble.com/gdal-dev-Is-it-possible-to-add-new-fields-to-a-shapefile-and-populate-then-tp5315568p5315653.html
Sent from the GDAL - Dev mailing list archive at Nabble.com.


More information about the gdal-dev mailing list