Faster Way to Check for and Delete GIS Data with Python

by | Jun 5, 2012

This is a guest post from Ann Stark (Twitter @StarkAnn) at The GIS Studio Blog.  Ann has put together some really nice posts on the subject of using Python with ArcGIS Desktop.  Check out her blog!

In repeated automated tasks, I often have to delete a set of data I am about to recreate fresh. ArcPy offers a delete function, but the faster way to delete is through the os module.

In this example, I have a folder of shapefiles that I overwrite every time I run the script.   The first step in my script is to make a list of existing shapefiles in the folder and then step through the list deleting them.  Ideally we would just use the arcpy.env.overwrite = True setting, however this does not work with the FCtoShapefile command. Using the ArcPy tools, this deleting process can be pretty slow. Using the os tools, we speed things up significantly.
There are a few checks that help keep errors at bay – the first being a check for the existence of your data folder.  Since the list I generate is of every file in the folder, the second check is to make sure there are not folders in my list of things to delete.  I only want to delete pieces of shapefiles.  Since this folder is only used for shapefile output I’m taking the chance that those are the only types of files in here.  Otherwise I’d be more careful to check for the .shp, .shx. .dbf file extensions.  In the event the shapefile folder has been deleted entirely, the last error check is to create the folder if it doesn’t exist at all.
Here’s the sample:


Recent Posts

Eric Pimpler
Eric is the founder and owner of GeoSpatial Training Services ( and has over 25 years of experience implementing and teaching GIS solutions using ESRI, Google Earth/Maps, Open Source technology. Currently Eric focuses on ArcGIS scripting with Python, and the development of custom ArcGIS Server web and mobile applications using JavaScript. Eric is the author of Programming ArcGIS with Python Cookbook - 1st and 2nd Edition, Building Web and Mobile ArcGIS Server Applications with JavaScript, Spatial Analytics with ArcGIS, and ArcGIS Blueprints. Eric has a Bachelor’s degree in Geography from Texas A&M University and a Master's of Applied Geography degree with a concentration in GIS from Texas State University.

Sign up for our weekly newsletter
to receive content like this in your email box.