I am trying to change the field value of a shapefile, but only in some specific features. However the code I have changes the value for all features in the shapefile. Is there any way of accessing the desired feature(s) in a simple way? This is what I have so far:
import ogr
driver = ogr.GetDriverByName('ESRI Shapefile')
file = '/home/src.shp'
dataSource = driver.Open(file, 1)
layer = dataSource.GetLayer()
feature = layer.GetNextFeature()
los = 1
while feature:
feature.SetField("LOS", los)
layer.SetFeature(feature)
feature = layer.GetNextFeature()
dataSource.Destroy()
Best Answer
You're almost there. You can get a specific feature by passing its ID to the
layer.GetFeature(id)
method. Assuming you know the ID of the feature, you have to update your code like this:Remember that ID's start at 0. So the ID of the last feature of your layer would be
layer.GetFeatureCount() - 1
.