Faster Way to Check for and Delete GIS Data with Python

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:

Want to learn more about using Python with ArcGIS 10 and ArcGIS 10.1?  We have a number of instructor led and self paced training opportunities.

Python ArcGIS Programming Bootcamp
Next Session: July 9th – August 10th

GIS Programming 101 for ArcGIS 10

GIS Programming 201 for ArcGIS 10

ArcGIS Programming with Python Bundle

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>