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: