Python module to delete SHP features (without Desktop GIS installed)

You can use the GDAL/OGR python API, the code will be like that:

from osgeo import ogr

shapefile = ogr.Open( "shapfile.shp",1 )
layer=shapefile.GetLayerByIndex(0)
count=layer.GetFeatureCount()
for feature in range(count):
    layer.DeleteFeature(feature)

The command line ogr2ogr with a where clause guaranteed to create empty results is one quick and easy method:

ogr2ogr output.shp input.shp -where "FID < 0"

The overview page for python and OGR (and GDAL) is http://trac.osgeo.org/gdal/wiki/GdalOgrInPython


You can do this in pyshp. It's simple but not obvious because I never envisioned this use case. But it does make sense for automated update applications. I tested the following 6 lines of code and it worked great:

import shapefile
r = shapefile.Reader("myshape")
w = shapefile.Writer(r.shapeType)
# This line will give us the same dbf schema
w.fields = r.fields
# Use the original bounding box as a place holder in the header
w.bbox = lambda: r.bbox
w.save("myshape")

You now have a shapefile written over the original that has correct headers and the original dbf fields. It will open safely in GIS software and shapefile libraries but has no features or dbf records.

The lambda function transfers the original bounding box over as a placeholder. You can put what ever float values you want in an array of [xmin, ymin, xmax, ymax]. Example:

w.bbox = lambda: [0.0, 0.0, 0.0, 0.0]

Changing dbf fields is simple too and documented in the pyshp docs.

Hope that helps.