Select to view content in your preferred language

Python: deletion of feature classes and tables except for those with specified names

2121
3
11-15-2013 06:24 AM
RichardCarr
New Contributor
Hello,
I would like to add a piece of python to the end of arcpy script that will search a file geodatabase and delete all files except for those in a list that I will specify. I am not sure where to start - so any ideas would be most welcome!

geodatabase: C:\...\ParcelProcessingShell.gdb
files to retain: "Template_TBL", "dbt_Assessors", "PARCELS"
Tags (2)
0 Kudos
3 Replies
T__WayneWhitley
Honored Contributor
Could do something like:
import arcpy
arcpy.env.workspace = r'C:\...\ParcelProcessingShell.gdb'  #your workspace path

keepers = ["Template_TBL", "dbt_Assessors", "PARCELS"]
for each in arcpy.ListFeatureClasses():
     if each not in keepers:
          try:
               arcpy.Delete_management(each)
          except:
               print 'oops, cannot delete ' + each


Of course, it looks like you have tables in there too?...if so, then you'll also need to use ListTables to return the listing on those and loop to delete tables not in 'keepers'...

Hope that helps,
Wayne
0 Kudos
RichardCarr
New Contributor
That worked perfectly. I did indeed need to have a separate loop for the tables, which worked as well. Thanks!
0 Kudos
ChrisSnyder
Honored Contributor
You also could use a wildcard(s) to denote the keeper group. Also a demo of a practical use of the Python set() object.

keeperString = "*_t"
keeperFcSet = set(arcpy.ListFeatureClasses(keeperString))
allFcSet = set(arcpy.ListFeatureClasses())
delFcSet = allFcSet.difference(keeperFcSet)
for delFc in delFcSet:
   try:
      arcpy.Delete_management(delFc)
   except:
      print "Can't delete " + str(delFc)
0 Kudos