Skip to content

Instantly share code, notes, and snippets.

@moosetraveller
Created February 5, 2022 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moosetraveller/5d0828ab757694102ae4f7085ab004d1 to your computer and use it in GitHub Desktop.
Save moosetraveller/5d0828ab757694102ae4f7085ab004d1 to your computer and use it in GitHub Desktop.
Delete Shapefile with Python

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment