2

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()
0

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:

import ogr

driver = ogr.GetDriverByName('ESRI Shapefile')
file = '/home/src.shp'
dataSource = driver.Open(file, 1)
layer = dataSource.GetLayer()
feature = layer.GetNextFeature()
los = 1
feat_id = 24  # change this for the actual ID

feature = layer.GetFeature(feat_id)
feature.SetField("LOS", los)
layer.SetFeature(feature)

dataSource.Destroy()

Remember that ID's start at 0. So the ID of the last feature of your layer would be layer.GetFeatureCount() - 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.