[GIS] Select Layer By Attribute using loop

arcgis-10.0arcpypython

I have 273 features in the feature class and i want to select them one by one and use the statement in the following code.

At the line:

*arcpy.SelectLayerByAttribute_management (fc1,"NEW_SELECTION","OBJECTID=79")*, 

The feature whose object id is 79 one of the features. When i use this code, I do it for only that feature. I want to apply the statement to all features one by one with a loop. I try to do it, but i am new for programming with python.

import arcpy
from arcpy import env
env.workspace = "D:\pomme de terre 2\pomme de terre2.gdb"
env.overwriteOutput = 1

fc1 = "Flowlin24K_sl_Uns"
fc2 = "New_Poyline"

arcpy.SelectLayerByAttribute_management (fc1,"NEW_SELECTION","OBJECTID=79")
arcpy.SelectLayerByLocation_management(fc1,"INTERSECT",fc1)
arcpy.SelectLayerByAttribute_management (fc1,"REMOVE_FROM_SELECTION","StreamLevel>6")
arcpy.CopyFeatures_management(fc1,"hidden")
arcpy.SelectLayerByAttribute_management (fc1,"CLEAR_SELECTION")

coordList = []

arcpy.FeatureVerticesToPoints_management("hidden", "vertices", "MID")
arcpy.AddXY_management("vertices")
rows = arcpy.SearchCursor("vertices")

for row in rows:
    X = row.getValue("POINT_X")
    Y = row.getValue("POINT_Y")
    coordList.append([X, Y])

del row, rows

coordList.sort()

point = arcpy.Point()
array = arcpy.Array()

for feature in coordList:
    point.X = feature[0]
    point.Y = feature[1]
    array.add(point)

polyline = arcpy.Polyline(array)

array.removeAll()
arcpy.Delete_management("vertices")
arcpy.Delete_management("hidden")
arcpy.CopyFeatures_management(polyline, fc2)

Best Answer

You can pull this off, but it's my understanding that you can't run selections on feature classes, only on feature LAYERS.

From ESRI: The input must be a feature layer or a table view. The input cannot be a feature class or table. ESRI SelectLayerByAttributes Help files

Your code requires a arcpy.MakeFeatureLayer_management() ESRI MakeFeatureLayer Help files Remember to delete the feature layer at the end of the loop

Since you've already got an understanding of search cursors, you could just use the cursor to identify the OID for each loop -- this would eliminate the possiblity of your index being out of range. Each time you loop through your code, change your where clause to the current row's OID.

If you're just getting into Python for ArcMap I HIGHLY recommend checking out Penn State's Online GIS Master's Program -- It's open courseware through the MIT Creative commons license.

Related Question