Feature Layer Search and Create Feature Layer from Selected Features

2607
3
Jump to solution
03-11-2015 09:46 AM
BradGagliano
New Contributor II

I am rather new to arcpy, however I am moving my AddIns from VB.net over to python.  I am trying to search for a feature layer(s) and if found check to see if they have a selection.  If so create a feature layer from that selection. If not do nothing.

I have attached a portion of the code I'm trying to use.

Thanks in advance.

Brad

0 Kudos
1 Solution

Accepted Solutions
BlakeTerhune
MVP Regular Contributor

Assuming this is the snippet of code you're asking about?

for lyr in arcpy.mapping.ListLayers(mxd, "CRASHES1999", df):

    if lyr == "CRASHES1999":

        desc = arcpy.Describe("CRASHES1999")

        in_table = "CRASHES1999"

        field_names = "YEAR"

        if desc.FIDSet:

            with arcpy.da.SearchCursor(in_table, field_names) as cursor:

                for row in cursor:

                    arcpy.MakeFeatureLayer_management(in_table, "SelectedCrashes1999")

        else:

            print "No Features Selected for CRASHES1999"

        del desc

        del in_table

        del field_names

Did you have a specific question or problem? Just guessing, but I see you're passing the field names for the search cursor as a string. According to the documentation, it needs to be a list or tuple. Try this instead:

field_names = ["YEAR"]

View solution in original post

0 Kudos
3 Replies
BradGagliano
New Contributor II

It seems I have answered my own question.

I had

if lyr == "CRASHES1997":

I should have had

if lyr.name == "CRASHES1997":

0 Kudos
BlakeTerhune
MVP Regular Contributor

Assuming this is the snippet of code you're asking about?

for lyr in arcpy.mapping.ListLayers(mxd, "CRASHES1999", df):

    if lyr == "CRASHES1999":

        desc = arcpy.Describe("CRASHES1999")

        in_table = "CRASHES1999"

        field_names = "YEAR"

        if desc.FIDSet:

            with arcpy.da.SearchCursor(in_table, field_names) as cursor:

                for row in cursor:

                    arcpy.MakeFeatureLayer_management(in_table, "SelectedCrashes1999")

        else:

            print "No Features Selected for CRASHES1999"

        del desc

        del in_table

        del field_names

Did you have a specific question or problem? Just guessing, but I see you're passing the field names for the search cursor as a string. According to the documentation, it needs to be a list or tuple. Try this instead:

field_names = ["YEAR"]

View solution in original post

0 Kudos
BradGagliano
New Contributor II

Thanks, this did seem to make it run smoother and quicker.

0 Kudos