0

I am using ArcPy with ArcMap 10.6.

I would like to know the ArcPy code to clear selected features in all layers. Just like the "Clear Selected Features" button works. I found Clearing Selected Features in ArcMap using ArcPy

This is the code given:

arcpy.SelectLayerByAttribute_management(Table, "CLEAR_SELECTION")

However, in the given code, you have to stipulate a table. I don't want to write code for every table/feature class. I would prefer code to clear ALL selected features.

Simply removing the table parameter does not work.

Found this, which seems to be on the right track: https://community.esri.com/thread/108712

However, when I run the below code, it executes, but nothing happens:

>>> import arcpy
... mxd = arcpy.mapping.MapDocument(r"FILEPATHHERE")
... df = arcpy.mapping.ListDataFrames(mxd, "Main")
... for lyr in arcpy.mapping.ListLayers(mxd,"",df):
...     print (lyr.name)+" ...is going to be cleared now. Running 'arcpy.SelectLayerByAttribute_management'"
...     arcpy.SelectLayerByAttribute_management(lyr, "CLEAR_SELECTION")
...     print (lyr.name)+" ...should be cleared now."
...     
Buildings ...is going to be cleared now. Running 'arcpy.SelectLayerByAttribute_management'
Buildings ...should be cleared now.
Site ...is going to be cleared now. Running 'arcpy.SelectLayerByAttribute_management'
Site ...should be cleared now.
>>>

I ran the same thing with @user2856’s suggestion:

>>> import arcpy
... mxd = arcpy.mapping.MapDocument(r"FILEPATHHERE")
... df = arcpy.mapping.ListDataFrames(mxd, "Main")
... for lyr in arcpy.mapping.ListLayers(mxd,"",df):
...     print (lyr.name)+" ...is going to be cleared now. Running...'"
...     lyr.setSelectionSet("NEW",set())
...     print (lyr.name)+" ...should be cleared now."
...     
Buildings ...is going to be cleared now. Running...'
Buildings ...should be cleared now.
Site ...is going to be cleared now. Running...'
Site ...should be cleared now.
>>>

Of course, I do not actually have “FILEPATHHERE” in my code; the correct, actual file path is there (just to be clear).

All selected features remain selected when executing the above code. If I run “arcpy.SelectLayerByAttribute_management(lyr, "CLEAR_SELECTION")” separately and individually on each layer, it works correctly and the selected features are deselected.

What’s the problem?

0

1 Answer 1

2
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\thisIsAnExamplePath\exampleMap.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
for lyr in arcpy.mapping.ListLayers(mxd,"",df):
    arcpy.SelectLayerByAttribute_management(lyr.name,"CLEAR_SELECTION")

I needed to pass the data frame as data frame object with [0], then use the ".name" to pass the layer name as a string into the parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.