I have two line feature layers, they intersect at mid point of each line segment at 90 degree angle. Let's say, they are Layer1 and Layer2, I want to iterate through Layer1 and use the SelectLayerByLocation tool to find the line segment from Layer2 that intersect it, then get its 'Name' field value and apply it to the Layer1's line segment's 'Name' field. I've searched a lot, couldn't find working ArcPy script for this to work, I have the following script to start with:

# open the Layer1 and Layer2
Layer1 = base_dir + 'conveyance.shp'
Layer2 = base_dir + 'sa2dcenterline.shp'

Lyr1 = ap.MakeFeatureLayer_management(Layer1, "barrel")
Lyr2 = ap.MakeFeatureLayer_management(Layer2, "sa2d")

# iterate through each line feature in Lyr2 to intersect with Lyr1
with ap.da.SearchCursor(Lyr2, ['SHAPE@', 'Name']) as cur:
    for row in cur:
        cur_intersect = ap.SelectLayerByLocation_management(Lyr1, "INTERSECT", row[0], '', 'NEW_SELECTION')
        # cnt = int(ap.GetCount_management(cur_intersect).getOutput(0))
        # if cnt > 0:
        #   print(f'{row[1]} intersects with {cnt} features.')
        lyr_sel = ap.MakeFeatureLayer_management(cur_intersect, "sel")

        # here is where I am trying to get the selected Lyr1's Name field
        # and assign it to Lyr2's feature's Name field, the following 
        # surely will fail as it is trying to assign to a tuple,
        # i included it here just as placeholder
        with ap.da.SearchCursor(lyr_sel, ['Name']) as cur1:
            for row_sel in cur1:
                row[2] = 'b-' + str(int(row_sel[0]))
        lyr_sel = None

As you can see from above, I can iterate through the records in Layer2 and select by intersection from Layer1, but then I couldn't find way to get the selected Layer1's feature and get to its attributes, then update the corresponding 'Name' field in Layer2.


1 Answer 1


The program is mostly correct. It needs two updates to make it work:

First, change with ap.da.SearchCursor(Lyr2, ['SHAPE@', 'Name']) as cur: to with ap.da.UpdateCursor(Lyr2, ['SHAPE@', 'Name']) as cur:

Second, change the bottom section of the code to:

with ap.da.SearchCursor(lyr_sel, ['Name']) as cur1:
    for row_sel in cur1:
        row[2] = 'b-' + str(int(row_sel[0]))

So, basically, need to make the update layer to be editable, and delete the temporary selection layer after each use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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