Python Module for Deleting SHP Features Without Desktop GIS

open-source-gispythonshapefile

I have a piece of software (not Arc) that runs nightly on a non-production machine which updates shapefile features from an external database. Periodically I would like to delete all of the features in the shapefile (not the file itself, which must remain) and let the software "rebuild" the shapefile from scratch. I would like to automate this process.

I don't have any GIS software currently installed on that machine. I was hoping that I could script a routine in Python that would automatically delete the features, much like Arc's Delete Features geoprocessing tool.

Are there any Python modules that would allow me to do this? Preferrably open-source? I looked at Shapely and PyShp but didn't see anything that would allow me to delete the features in mass or that matched a WHERE clause. They can write features and analyze them, but haven't seen DELETE FEATURES functions anywhere.

I must certainly be missing something simple…

EDIT : I have 35 folders (different geographic extents, all in their own projection), with 35-65 shapefiles with makes around 1000 shapefiles to deal with.

Best Answer

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)