I have an arcpy script which is bringing layers within a workspace into the table of contents, checking whether they contain features within the "current" extent of the mxd, and removing them if they are not. my script is as follows:
mxd = arcpy.mapping.MapDocument ("CURRENT") arcpy.env.workspace = 'Database Connections\database.sde' arcpy.env.overwriteOutput = True df = arcpy.mapping.ListDataFrames(mxd, "*") arcpy.env.extent = df.extent dsList = arcpy.ListDatasets("", "Feature") for ds in dsList: fcList = arcpy.ListFeatureClasses("*","",ds) for FC in fcList: try: addLayer = arcpy.mapping.Layer(FC) addLayer.name = FC addLayer.visible = False arcpy.mapping.AddLayer(df,addLayer,"AUTO_ARRANGE") for lyr in arcpy.mapping.ListLayers(mxd,""): cnt = int(arcpy.GetCount_management(lyr).getoutput(0)) if cnt<1: arcpy.mapping.RemoveLayer(df,lyr) del addLayer except: print "problem with: " + str(FC) pass del FC del fcList print 'finished' arcpy.RefrechTOC() arcpy.RefreshActiveView() arcpy.AddMessage("Appropriate Feature Layers Added") mxd.save del mxd
This script works, but the trouble is, the database that I am working with has become larger than it used to be, so much so that this tool takes too long to run now for it to be useful.
Question: is there a way to call arcpy.mapping.RemoveLayer() outside of the 'for' loop of arcpy.mapping.ListLayers() in order to cut the size of the list the loop checks to 1?