Python Equivalent of ModelBuilder’s Iterate Feature Selection

arcgis-desktoparcpylayerspython

My data consists of two featureclasses:

  1. Points = points representing trees
  2. Polygons = Polygons representing % canopy area by area. Each polygon in the FC has a % canopy measurement in the attributes.

I am trying to accomplish the following:

  1. Select points underneath polygon features
  2. For the points under each polygon, delete X% of the points based on
    the polygon attribute

The screenshot (Figure 1) shows a ModelBuilder only tool called Iterate Feature Selection. What is the correct Python scripting method to iterate through features in a feature class in order to pass the feature off to the SelectLayerByLocation_management command?

Figure 2 shows the output of the select by location. All 4 layers are the same, which will be a problem when I try and delete points by the canopy % measurement.

This is what I have tried so far:

import arcpy
from arcpy import env

env.overwriteOutput = True
env.workspace = r'C:\temp_model_data\OutputData'
outWorkspace = env.workspace

# The polygons have canopy % data in attributes
polygons = r'C:\temp_model_data\CanopyPercentages.shp'
points = r'C:\temp_model_data\points_20_2012.shp'

if arcpy.Exists("pointsLayer"):
    print "pointsLayer exists already"
else:
    arcpy.MakeFeatureLayer_management (points, "pointsLayer")
    print "pointsLayer created"

count = 1

#Create a search cursor to step through the polygon features
polys = arcpy.da.SearchCursor(polygons, ["OID@", "SHAPE@"])

for poly in polys:

    # Create a name for the polygon features
    count = count + 1
    featureName = "polygon_" + str(count)
    print featureName

    # Select points that lie under polygons
    arcpy.SelectLayerByLocation_management('pointsLayer', 'intersect', polygons)
    arcpy.SaveToLayerFile_management('pointsLayer', outWorkspace + featureName + ".lyr", "ABSOLUTE")

    # Add the random point selection script here...

    # Delete selected points within each polygon based on the % canopy cover...

Figure 1
enter image description here

Figure 2
enter image description here

Best Answer

Nick Ochoski is right about the SearchCursor, but there is a cleaner way to use it WITHOUT a while and manually calling next:

import arcpy
fc = "c:/data/base.gdb/roads"
field = "StreetName"
cursor = arcpy.SearchCursor(fc)
for row in cursor:
    print(row.getValue(field))
Related Question