AnsweredAssumed Answered

Python Script to Snap by Attribute Not Working

Question asked by wysorj on Jul 20, 2018
Latest reply on Oct 3, 2018 by wysorj

I have two point feature layers.  One represents cleaning and the other catch basins.  The cleaning layer exists as a hosted feature service in ArcGIS Online.  In ArcGIS Pro, I am trying to run the below code to snap cleaning points to catch basin points so they are coincident.  It only runs through the main loop one time.  It used to run fine but now I can't figure out why.  I am not a programmer so I am hoping someone that is can help me figure out why my code won't loop more than once.  Any ideas?  Thanks!

arcpy.env.overwriteOutput = True
arcpy.env.workspace = "E:\MDC\Catch Basin Cleaning\map_docs\Catch Basin Cleaning 2018\Inspection 2018 Review.gdb"

cleaning_fc = 'Cleaning and Sediment Monitoring'
catchBasin_fc = 'ssCatchbasin'
objId_field = 'OBJECTID'
name_field = 'SAPLINKID_FK'
name_field2 = 'SAPLINKID'

#Create a where clause based on the cleaning date
aCleanDateWhereClause = "CleanDate >= timestamp '2018-06-26 01:10:00'"
aTownWhereClause = "TOWNCODE = '01'"

#Create layer files
cleaning_layer = arcpy.MakeFeatureLayer_management(cleaning_fc, "cleaning_lyr", aCleanDateWhereClause)
catchbasin_layer = arcpy.MakeFeatureLayer_management(catchBasin_fc, "catchbasin_lyr", aTownWhereClause)

#Clear any selections
arcpy.management.SelectLayerByAttribute(cleaning_layer , "CLEAR_SELECTION")
arcpy.management.SelectLayerByAttribute(catchbasin_layer , "CLEAR_SELECTION")

#Create a search cursor using an SQL expression to count
#total number of cleaning records to be snapped
totalRec = 0
with arcpy.da.SearchCursor(cleaning_layer, [objId_field, name_field]) as cursor:
     for row in cursor:
          totalRec += 1
     print ("Total Cleaning Recs:  " + str(totalRec)) #I get 734 records here

#Create a search cursor using an SQL expression to loop through only
#those points that have been created since a specific date.  Snap those
#cleaning points to the ssCatchbasin so they are coincident
curRec = 0 #counter for keep tracking of where we are in the loop

#the same loop below only runs one time
with arcpy.da.SearchCursor(cleaning_layer, [objId_field, name_field]) as cursor:
     for row in cursor:
          curRec += 1
          sapLinkId = row[1]
          if "GIS" in sapLinkId:
               layer1 = arcpy.management.SelectLayerByAttribute(cleaning_layer , "NEW_SELECTION", "SAPLINKID_FK=" +"'"+row[1]+"'")
               layer2 = arcpy.management.SelectLayerByAttribute(catchbasin_layer , "NEW_SELECTION", "SAPLINKID=" +"'"+row[1]+"'")
               arcpy.Snap_edit(layer1, [[layer2, "VERTEX", "120000 feet"]])

               percentDone = round((curRec/totalRec)*100,0)
               print("Processing row " + str(row[0]) + " for SAPLINKID " + row[1] + " ("+ str(percentDone) + "% percent complete)")

print ("Done!")

Outcomes