Sunday 22 September 2019

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



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.



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)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...