0

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.

  • Try adjusting your whereclause : exp = """{} = {}""".format(arcpy.AddFieldDelimiters(infc, field), iterateValue) (or exp = """{} = '{}'"""format(arcpy.AddFieldDelimiters(infc, field), iterateValue) if your field is string). – smiller Sep 27 at 15:38
  • @smiller thank you! Updated, and it still doesn't loop :( – ElTajibo Sep 27 at 17:38
0

It looks like you have arcpy.env.overwriteOutput set to True. With each iteration you are copying over whatever you have ExportBuffer set as. Currently you have a single feature class that's been copied over with each iteration, giving the appearance that the loop only iterated one row. You'll need to update your output feature class name in variable ExportBuffer with each iteration to a unique name to prevent copying over the previous loop's results.

  • My apologies - I changed some parameters from my original code before posting this question but forgot to change ExportBuffer to 'outfc'; it's now updated in my question. – ElTajibo Sep 27 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.