Deleting selected features from Vector/OGR in GDAL/Python?

You're passing a Feature object to layer.DeleteFeature which is expecting an integer value (a feature ID or "FID"), not a Feature object.

Try passing the FID instead:

for feat in layer:
    print feat.GetField("Area")
    layer.DeleteFeature(feat.GetFID())

Note that the OGR layer.DeleteFeature(fid) method doesn't actually delete features, it just marks them as deleted in the .dbf then ignores them. This is mentioned in the shapefile driver doc:

Deleted shapes are marked for deletion in the .dbf file, and then ignored by OGR. To actually remove them permanently (resulting in renumbering of FIDs) invoke the SQL 'REPACK ' via the datasource ExecuteSQL() method.

For more info, see GetFeatureCount gives same result after deleting a feature.


It works using that code:

shapefile = ogr.Open(file.shp, 1)
layer = shapefile.GetLayer()
layer.SetAttributeFilter("Area < 5000")

for feat in layer:
    print feat.GetField("Area")
    layer.DeleteFeature(feat.GetFID())
    shapefile.ExecuteSQL('REPACK ' + layer.GetName())

Tags:

Python

Gdal

Ogr