I have a layer where features are selected by location in relation to one or more other layers (selection_type is ADD_SELECTION) in a loop. After that, zero, one, some or all features are selected.
I want to delete only the selected features - if there are some.
But the "Delete Features"-Tool deletes either the selected features, or - if none are selected - all of them. How can I check, if there are any features selected? The "Get Count"-Tool works just like the "Delete Features"-Tool,
E.g. Layer X has a total of 100 features:
- No features are selected, "Get Count" returns 100
- All features are selected, "Get Count" returns 100
I would like to delete only the selected features. If there are none, I don't want to delete anything.
-
1Use layer getSelectionSet method.FelixIP– FelixIP2018年09月04日 08:32:54 +00:00Commented Sep 4, 2018 at 8:32
-
@FelixIP: I don't have a MXD. It is a temporary layer, created in arcpy. How can I access it's methods?Greg Z– Greg Z2018年09月05日 09:12:22 +00:00Commented Sep 5, 2018 at 9:12
-
@FelixIP: OK, you can access the layer from the result set of "arcpy.MakeFeatureLayer_management". Then you can use the "getSelectionSet" method. Thanks a lot! Please make your comment an answer, so I can accept it :-)Greg Z– Greg Z2018年09月05日 09:27:01 +00:00Commented Sep 5, 2018 at 9:27
-
You can also use FIDSet on a Describe object created from a Layer object, returns ID's of selection, seach help for "FIDSet".Hornbydd– Hornbydd2018年09月05日 11:27:14 +00:00Commented Sep 5, 2018 at 11:27
2 Answers 2
Use the layer property FIDSet
. It returns a string of selected features' OIDs. If no features are selected it returns an empty string.
if arcpy.Describe ("layer").FIDSet:
arcpy.DeleteFeatures_management ("layer")
-
Thanks @Emil! I accepted Felix' answer, because he was the first to respond.Greg Z– Greg Z2018年09月06日 07:25:19 +00:00Commented Sep 6, 2018 at 7:25
-
I wanted to acknowledge Felix, because his first comment on my question already fixed my problem. Thank you, anyway!Greg Z– Greg Z2018年09月07日 13:02:24 +00:00Commented Sep 7, 2018 at 13:02
Yes, I used FIDset property before to deal with existing selection.
getSelectionSet is something relatively new (10.4 ?) and very handy, because it provides list of OIDs, no need to split FIDset string and convert it to numbers when required.
I also found it's sibling setSelectionSet being the very useful property. I use it when possible to replace clumsy select layer by attribute, where SQL clause IN (...) can be extremely slow.
Makes me wonder why did it take so long to implement. Selection handling in grandmother ArcView 3 was/is very efficient and lightning fast.
Explore related questions
See similar questions with these tags.