I'm trying to iteratively select and export a layer using da.SearchCursor, but the loop stops after the first iteration. Here is the code:
arcpy.env.workspace = ScratchGDB #
infc= "PA"
field = 'UniqueID'
arcpy.MakeFeatureLayer_management(infc, "infcLyr")
for row in arcpy.da.SearchCursor(infc, field):
iterateValue = row[0]
exp = field + " = '" + iterateValue + "'"
outfc = ScratchGDB + iterateValue
if arcpy.Exists(outfc):
print ("skip - output exists") # skip row if it has been exported already
else:
selectRow = arcpy.SelectLayerByAttribute_management("infcLyr", "NEW_SELECTION", exp)
arcpy.CopyFeatures_management("infcLyr", outfc)
However, when I use a similarly structured code, but instead of exporting, I just printed the output path, the loop worked fine:
arcpy.env.workspace = ScratchGDB #
infc= "PA"
field = 'UniqueID'
arcpy.MakeFeatureLayer_management(infc, "infcLyr")
for row in arcpy.da.SearchCursor(infc, field):
iterateValue = row[0]
exp = field + " = '" + iterateValue + "'"
outfc = ScratchGDB + iterateValue
if arcpy.Exists(outfc):
print ("skip - output exists") # skip row if it has been exported already
else:
print(outfc)
Update:
I tried to set the arcpy.env.overwriteOutput
to FALSE
following the suggestion by @Emil Brundage. The loop still stops after both SelectLayerByAttribute_management
and CopyFeatures_Management
run for the first time.
Note that the first part of the if
statement loops with no problem; i.e., if there are multiple existing outputs, the loop will skip all of them. It only stops after the select
and copy
tools run through their first input row.
exp = """{} = {}""".format(arcpy.AddFieldDelimiters(infc, field), iterateValue)
(orexp = """{} = '{}'"""format(arcpy.AddFieldDelimiters(infc, field), iterateValue)
if your field is string).