0

Trying to Create a for loop within a script and for some reason, it returns only the last row? The script will go onto geoprocess on each row, but for some reason it doesn't want to play the game,

I think it must be syntax related, but not sure where?

import arcpy
from arcpy import env
import time


#Settings
baseDirectory = 'B:\\Non_Contigous_Working'
fileworkspace = baseDirectory + '\\Non_Contiguos_Working.gdb'
Holdings = fileworkspace + '\\Holding\\NTLLS_Holding_190617'

#arcpy Settings
arcpy.env.overwriteOutput = True
env.workspace = fileworkspace

#SearchCursor
arcpy.MakeFeatureLayer_management(Holdings, 'Holdings_Layer')

with arcpy.da.SearchCursor(Holdings, ['Holding_Reference_Number']) as Holdings_Ref_cursor:
for row in Holdings_Ref_cursor:
       refNumber = str(row[0])
print 'Holding:' + refNumber
7

The reason your're only getting the last row searched is because the print statement is out of scope of the loop thus refNumber will have the value of the last searched row.

To rectify this indent your print statement and any other code relating to each iteration in line with refNumber = str(row[0]):

with arcpy.da.SearchCursor(Holdings, ['Holding_Reference_Number']) as Holdings_Ref_cursor:
    for row in Holdings_Ref_cursor:
        refNumber = str(row[0])
        print 'Holding:' + refNumber

The for loop also needs to be indented to make the cursor in scope for the for row in Holdings_Ref_cursor: loop.

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.