Thursday, 21 April 2016

arcgis 10.1 - Using Select Layer By Attribute in for loop with ArcPy?


I'm trying to iterate through a feature class and select each feature one by one by using the OBJECTID field. When I use a single value, the SelectLayerByAttribute works, but how do I compare the OBJEECTID to a variable that increases in count through the loop. The program is then suppose to create a layer for each feature in the feature class. This is what I have so far:


import arcpy
import os
arcpy.env.workspace = "C:\Users\Daimon Nurse\Desktop\DFMPROJECT\DFMPROJECT.gdb"
arcpy.env.overwriteOutput=True
inlayer = "C:\Users\Daimon Nurse\Desktop\DFMPROJECT\DFMPROJECT.gdb\ZonesPolyline"



with arcpy.da.SearchCursor(inlayer, ("OID@", "SHAPE@AREA")) as cursor:
i = 1
for row in cursor:
print("Feature {0} has an area of {1}".format(row[0], row[1]))
outlayer = "ZonePolygon"
arcpy.MakeFeatureLayer_management (inlayer, outlayer)
arcpy.SelectLayerByAttribute_management (outlayer, "NEW_SELECTION", """ "OBJECTID" = 1 """)
output = r'C:\Users\Daimon Nurse\Desktop\Grounds Project\DFMGROUNDS.gdb'
outfile = os.path.join (output, i)
arcpy.CopyFeatures_management(outlayer, outfile)

print i
i = i + 1

Answer



Instead of using a where_clause of:


"""           "OBJECTID" = 1 """

I think you should try:


'"OBJECTID" = {0}'.format(i)

Also, instead of:



outfile = os.path.join (output, i)

try:


outfile = os.path.join(output, "fc{0}".format(i))

What I have used in both of the above is Python string formatting. Python strings can be delimited using single or double quotes. I used single in the first so as not to clash with double quotes that indicated the field name. In the second I used double quotes because I think they look better.


I added "fc" to your feature class name because I don't think ArcGIS will like a feature class name that is, or starts with, a number.


Also take a look at:


arcpy.env.workspace = "C:\Users\Daimon Nurse\Desktop\DFMPROJECT\DFMPROJECT.gdb"
arcpy.env.overwriteOutput=True

inlayer = "C:\Users\Daimon Nurse\Desktop\DFMPROJECT\DFMPROJECT.gdb\ZonesPolyline"

which needs to escape the single backslashes in your pathnames e.g.:


arcpy.env.workspace = r"C:\Users\Daimon Nurse\Desktop\DFMPROJECT\DFMPROJECT.gdb"
arcpy.env.overwriteOutput=True
inlayer = r"C:\Users\Daimon Nurse\Desktop\DFMPROJECT\DFMPROJECT.gdb\ZonesPolyline"

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...