Arcpy: Make sure there's selection before execute 'Copy Features"

1217
2
Jump to solution
08-31-2018 04:19 PM
helenchu
Occasional Contributor II

Hi

I use "Copy Features" tool to make a layer from selection.  It's crucial that I check for a selection first or it will copy the whole layer.  Please help me with that.  Thank you!

Tags (1)
0 Kudos
1 Solution

Accepted Solutions
RandyBurton
MVP Alum

And something like this should also work:

selection = arcpy.SelectLayerByAttribute_management(layer, "NEW_SELECTION",
                                                    where_clause="Field = 'Something'")

result = arcpy.GetCount_management(selection)
count = int(result.getOutput(0))
if count:
    print count
    arcpy.CopyFeatures.......
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

See: Get Count

You could use GetCount to count items in the layer before and after the selection and if selection is less than the original count and greater than zero then do the copy.

View solution in original post

2 Replies
DanPatterson_Retired
MVP Emeritus

for map and pro

Layer—ArcPy | ArcGIS Desktop 

getSelectionSet ()

Returns a layer's selection as a Python set of object IDs.

which will be > 0 if there is a selection.

If you don't have a layer, then use MakeFeatureLayer first then delete if needed

RandyBurton
MVP Alum

And something like this should also work:

selection = arcpy.SelectLayerByAttribute_management(layer, "NEW_SELECTION",
                                                    where_clause="Field = 'Something'")

result = arcpy.GetCount_management(selection)
count = int(result.getOutput(0))
if count:
    print count
    arcpy.CopyFeatures.......
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

See: Get Count

You could use GetCount to count items in the layer before and after the selection and if selection is less than the original count and greater than zero then do the copy.