[gdal-dev] Is it possible to add new fields to a shapefile and populate then?
woodbri at swoodbridge.com
Mon Apr 3 23:54:58 PDT 2017
On 4/3/2017 11:37 PM, jratike80 wrote:
> Stephen Woodbridge wrote
>> Hi All,
>> I have a shapefile(s) and I want to read the features, generate some
>> metrics about each feature and then add them to the that feature. I'm
>> using python and one obvious way to to in effect create a new shapefile
>> with the columns I need to add, then copy the existing shapefile to the
>> new one adding the additional metrics.
>> I wondering if I can add the new columns to the shapefile, then do a
>> read and update.
>> Pros and cons to these approaches? and how to do the later one if
>> I looked at the python gdal/ogr cookbook and didn't this specific
>> example. But I thinking of something along the lines of:
>> 1. open the dataset for read/write
>> 2. layer.CreateField() to add the new fields
>> 3. loop through the features in the layer
>> 4. and use feature.SetField()
>> 5. and feature = None to commit the changes
>> will this work?
> You can demonstrate that it is possible with ogrinfo:
> ogrinfo -sql "alter table test add column foo integer" test.shp
> ogrinfo -dialect sqlite -sql "update test set foo=2" test.shp
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)
layer = dataSource.GetLayer()
for feature in layer:
geom = feature.GetGeometryRef()
feature = None
dataSource = None
In the cookbook example for "Create a New Shapefile and Add Data" there
is a call to:
but I do not see an equivalent call for:
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.
This email has been checked for viruses by Avast antivirus software.
More information about the gdal-dev