You can use arcpy.management.Delete
:
import arcpy
shapefile = r"D:\projects\playground\python\stackgis\data\test.shp"
if arcpy.Exists(shapefile):
arcpy.management.Delete(shapefile)
Alternatively, you could use GDAL/OGR:
import os
from osgeo import ogr # conda install -c conda-forge gdal
shapefile = r"D:\projects\playground\python\stackgis\data\test.shp"
driver = ogr.GetDriverByName("ESRI Shapefile")
if os.path.exists(shapefile):
driver.DeleteDataSource(shapefile)
Or, you could write your own function to delete the shapefile along with the associated files:
import os
from pathlib import PurePath
shapefile_extensions = [
"shp", "shx", "dbf", "sbn", "sbx", "fbn",
"fbx", "ain", "aih", "atx", "ixs", "mxs",
"prj", "xml", "cpg"
]
def delete_shapefile(shapefile):
if os.path.exists(shapefile):
path = PurePath(shapefile)
os.remove(shapefile)
for extension in shapefile_extensions:
associated_file = f"{path.parent}\\{path.stem}.{extension}"
if os.path.exists(associated_file):
os.remove(associated_file)
shapefile = r"D:\projects\playground\python\stackgis\data\test.shp"
delete_shapefile(shapefile)
Something to consider: delete_shapefile
deletes files based on the shapefile's name and the associated file extensions.
That can lead to an unwanted side effect: If someone names an unrelated XML file (or another file with a shapefile-associated extension) same as the shapefile, that file will be deleted as well.
However, the question would be, does ogr
and/or arcpy
do a deep check? I don't know.