0

I have a script that selects all addresses within a polygon (also multi polygons), and then sums a column "Anzahl" from those selected addresses. The Sum is then written to the Polygon in the column Anzahl.

Problem is, it only works on a single selected polygon. If I select multiple polygons it breaks line 33:

line 33, in <module>
    edit.stopEditing(True)
RuntimeError: start edit session

How can I change this start/stop edition to let it work on multiple selected polygons.

The goals is for each polygon select the addresses inside, sum the column "Anzahl" of the selected addresses. And write the sum, to that polygon.

import arcpy

# Get Parameters
polygon_layer = arcpy.GetParameterAsText(0)
address_layer = arcpy.GetParameterAsText(1)

selected_oids = []
with arcpy.da.SearchCursor(polygon_layer, "OID@") as cursor:
    for row in  cursor:
        selected_oids.append(row[0])

workspace = arcpy.Describe(polygon_layer).path

anzahl_total = 0
try:
    edit = arcpy.da.Editor(workspace)
    edit.startEditing(False, True)
    for oid in selected_oids:
        arcpy.SelectLayerByAttribute_management(polygon_layer, "NEW_SELECTION", "OBJECTID = {0}".format(oid))
        arcpy.SelectLayerByLocation_management(address_layer, "WITHIN", polygon_layer)
        #address_count_within = int(arcpy.GetCount_management(address_layer).getOutput(0))
        #arcpy.AddMessage('Number of address points within Polygon (OBJECTID={0}): {1}'.format(oid, address_count_within))
        with arcpy.da.SearchCursor(address_layer, "Anzahl") as cursor:
            for row in cursor:
                anzahl_total = anzahl_total + row[0]
        #print anzahl_total
            #edit.startOperation()  
            with arcpy.da.UpdateCursor(polygon_layer, ["anzahl"]) as cursor:
                for row in cursor:
                    row[0] = anzahl_total
                    cursor.updateRow(row)
            #edit.stopOperation()
    edit.stopEditing(True)  


finally:
    pass
    # qry = "OBJECTID IN ({0})".format(','.join([str(o) for o in selected_oids]))
    # arcpy.SelectLayerByAttribute_management(polygon_layer, "NEW_SELECTION", qry)
  • 3
    Just a quick tip - are you aware of the Spatial Join GP tool? It will let you do just that and you can call it from arcpy Python code just as any other GP tool. – Alex Tereshenkov Sep 16 '18 at 15:41
  • 1
    And you don't need editing session. – FelixIP Sep 16 '18 at 19:03
  • 1
    When presenting code here I think it is almost always better to remove try/except statements because they can mask useful error messages. – PolyGeo Sep 16 '18 at 20:01
  • You don't need to start an editing session for an update cursor. – Emil Brundage Sep 17 '18 at 20:21

Your Answer

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

Browse other questions tagged or ask your own question.