5

This is my code:

num1 = layer.GetFeatureCount()
layer.DeleteFeature(1)
layer.SyncToDisk()
num2 = layer.GetFeatureCount()
print num1
print num2

For some reason, num1 and num2 are the same number. Why? Shouldn't deleting the feature make the FeatureCount smaller by 1?

3
  • Layer is probably stored to memory, try reloading the layer variable Dec 4, 2016 at 21:28
  • Nothing changed, same result
    – shittihs
    Dec 4, 2016 at 21:30
  • Do you have a feature with ID=1? If you do not, nothing gets deleted. Otherwise it looks like you are doing the same as in stackoverflow.com/questions/34950627/… which was said to work.
    – user30184
    Dec 4, 2016 at 21:50

1 Answer 1

7

It's because 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.

What the doc doesn't say is why GetFeatureCount still returns the same number after the "delete". According to the (current) main developer, it's because iterating over all features to recount is potentially expensive:

Yes, the GetFeatureCount() implementation of OGRShapeLayer returns the number of records, both the valid and invalid ones. To get the number of features (= valid records), it would have to iterate over each record, which is a potentially lengthy operation.

To get the correct number of features:

yourdatasource.ExecuteSQL('repack yourlayername')

This won't be as big an issue in GDAL 2.2 as:

Starting with GDAL 2.2, REPACK is also done automatically at file closing, or at FlushCache()/SyncToDisk() time, since shapefiles with holes can cause interoperability issues with other software.

BUT note this bug report if you are on Windows (fixed in GDAL 2.1.2):

Shapefile REPACK cause corruptions on Windows

...the current behaviour of REPACK that attempts to delete the existing .dbf, .shp, .shx and rename the _packed.dbf, ... as .dbf, .shp, .shx fails because there might be still file descriptors open on the .dbf, .shp, .shx in the current process or in other processes. The only reliable solution in this case is to modify in place the content of the files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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