Looping ArcPy function through each point in shapefile

arcgis-proarcpyfor loopspatial-analyst

I have been trying to create a geoprocessing tool to delineate watershed basins for each point in a shapefile (parameter 1; CROSSING). The code below returns three 'basins', but they are all identical to each other. How can I alter this code to return a unique 'basin' for each point in 'CROSSING'?

import arcpy
from arcpy import env
from arcpy.sa import *
arcpy.env.addOutputsToMap = True
#DEFINE PARAMETERS & zLimit
DEM         = arcpy.GetParameterAsText(0) #digital elevation model
CROSSING    = arcpy.GetParameterAsText(1) #shp containing the stream crossings
PARCEL      = arcpy.GetParameterAsText(2) #polygon for clipping raster layer
EXTENT      = arcpy.GetParameterAsText(3) #search radius for SnapPourPoint()
LOCATION    = arcpy.GetParameterAsText(4) #output file path
zLimit      = 3.2808                      #for converting meters to feet
#CHECK OUT REQUIRED EXTENSION
arcpy.CheckOutExtension("Spatial")
#CLIPPING RASTER LAYER TO SMALLER AREA AROUND THE PARCEL
AOI = arcpy.Buffer_analysis(PARCEL,'AOI',10000)
USR = ExtractByMask(DEM,AOI)
arcpy.AddMessage('Raster optimization completed')
#GENERATING REQUIRED RASTER LAYERS
outFill = Fill(USR,zLimit)
outFlowDir = FlowDirection(outFill)
outFlowAcc = FlowAccumulation(outFlowDir)
#SETUP FOR LOOP
crossings = arcpy.SearchCursor(CROSSING)
i = 1
for OBJECTID in crossings:
    outSnapPoint = SnapPourPoint(CROSSING, outFlowAcc, EXTENT)
    arcpy.AddMessage('Flow direction analysis completed')
    watersheds = Watershed(outFlowDir,outSnapPoint,"VALUE")
    arcpy.RasterToPolygon_conversion(watersheds,LOCATION+"/BASIN_"+str(i)+'.shp')
    arcpy.AddMessage('Basin '+str(i)+' completed')
    arcpy.Delete_management(outSnapPoint)
    arcpy.Delete_management(watersheds)
    i = i + 1
arcpy.AddMessage('Watershed basins have been drawn, and are located in '+LOCATION)   
#DELETE EXCESS SHAPEFILES
EXCESS = [outFill,outFlowDir,outFlowAcc,outSnapPoint,watersheds,AOI,USR]
arcpy.Delete_management(EXCESS)

Best Answer

Following some observations...

with arcpy.da.SearchCursor(CROSSING, ["OID@"]) as cursor:
  for row in cursor:
    where_clause = "OBJECTID = '{}'".format(row[0])
    layer_Select=arcpy.SelectLayerByAttribute_management(CROSSING, 'NEW_SELECTION', where_clause)
    outSnapPoint = SnapPourPoint(layer_Select, outFlowAcc, EXTENT)
    arcpy.AddMessage('Flow direction analysis completed')
    watersheds = Watershed(outFlowDir,outSnapPoint,"VALUE")
    arcpy.RasterToPolygon_conversion(watersheds,LOCATION+"/BASIN_"+str(i)+'.shp')
    arcpy.AddMessage('Basin '+str(i)+' completed')
    arcpy.Delete_management(outSnapPoint)
    arcpy.Delete_management(watersheds)
    i = i + 1

And if it doesn't work, you might need to export the selected feature to another shapefile before using it...

Related Question