3

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()
  • what is you criteria for choosing which features to change? – Ian Turton Jul 9 '19 at 10:47
  • I know the ID of the feature I want to change – rocker996 Jul 9 '19 at 11:06
  • there is nothing in your code to make use of the ID – Ian Turton Jul 9 '19 at 12:12
  • I don't know how to access the ID – rocker996 Jul 9 '19 at 13:05
  • You might like the Python ogr cookbook, pcjericks.github.io/py-gdalogr-cookbook – klewis Jul 9 '19 at 21:45
1

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.