Is there a way to remove layers from the Table of Contents if no features are present?

1272
3
03-16-2022 10:10 AM
David_Brooks
MVP Regular Contributor

Is there a tool or python script out there that can look through a Map in Pro, and remove any layers that are empty? I have about 30-40 layers that reference 5 feature classes in a GDB. They have queries on them to make 30-40 separate layers whjich i then need to export to CAD. It would be great to have a tool that removes the empty layers (as a result of the queries) before exporting. Otherwise the CAD DWG will contain a bunch of empty layers.


David
..Maps with no limits..
0 Kudos
3 Replies
JakeSkinner
Esri Esteemed Contributor

@David_Brooks,

You could so something like below:

import arcpy

project = r"C:\Projects\Example.aprx"

aprx = arcpy.mp.ArcGISProject(project)
for m in aprx.listMaps():
    print(f"Map: {m.name}")
    for lyr in m.listLayers():
        print(f"\t{lyr.name}")
        if lyr.isBasemapLayer == False:
            results = arcpy.GetCount_management(lyr)
            count = results.getOutput(0)
            if count == '0':
                print(f"Removing {lyr.name}")
                m.removeLayer(lyr)
aprx.save()
0 Kudos
David_Brooks
MVP Regular Contributor

@JakeSkinner thanks for the example, but that returns an error

David_Brooks_0-1647464749696.png

any ideas?


David
..Maps with no limits..
0 Kudos
JakeSkinner
Esri Esteemed Contributor

Replace the print statements to arcpy.AddMessage instead.  This will print which layer the script is failing on, and this should give us some insight on what's going on.  Ex:

arcpy.AddMessage(f"\t{lyr.name}")