Search code examples
pythonarcgisarcpy

how can I update records values based on value in another field using da update cursor?


I am trying to write file names and paths to two separate fields in a feature class, and the value for each record is dependent on finding a match in a list. When I run my code it writes the same values for each record, so something is going wrong. I think its finidng the first match and writing that value over and over, but I want it to look at the value in the field my search cursor is set to, and then find the match in the list and write that out to the two fields. What am I missing?

import arcpy, os
photos_path = r'P:\Records\GIS\Projects\D04_OHS\OverheadSignStructurePics'
OHS_FC = r'D:\Records\GIS\Projects\D04_OHS\D04_OHS.gdb\D04_OHS'
ID_fld = 'OSMI_ID'
file_nm_fld = 'LINK_FILENAME'
path_fld ='LINK_PATH'
photos_list = []

for dirpath, dirnames, filenames in os.walk(photos_path):
    for filename in filenames:
        fullPath = dirpath+'\\'+filename
        if fullPath not in photos_list:
            photos_list.append(fullPath)

arcpy.AddField_management(OHS_FC,file_nm_fld,'TEXT',100)
arcpy.AddField_management(OHS_FC,path_fld,'TEXT',300)
srch_cursor = arcpy.da.SearchCursor(OHS_FC,ID_fld)
updt_cursor_fn = arcpy.da.UpdateCursor(OHS_FC,file_nm_fld)
updt_cursor_fp = arcpy.da.UpdateCursor(OHS_FC,path_fld)
for row in srch_cursor:
    val = str(row[0])
    for p in photos_list:
        f_name, f_path = os.path.split(p)
        if val in p:
            #print val
             for u_row1 in updt_cursor_fn:
                u_row1[0] = f_name
                updt_cursor_fn.updateRow(u_row1)
             for u_row2 in updt_cursor_fp:
                u_row2[0] = f_path
                updt_cursor_fp.updateRow(u_row2)

Solution

  • You don't need the search cursor or the separate update cursors. Simply use a single update cursor and use that to both find the match and update the fields. Make sure to add all the fields you will need to the update cursor.

    fields = (ID_fld,file_nm_fld,path_fld)
    updt_cursor = arcpy.da.UpdateCursor(OHS_FC, fields)
    for row in updt_cursor:
        val = str(row[0])
        for p in photos_list:
            f_name, f_path = os.path.split(p)
            if val in p:
                #print val
                row[1] = f_name
                row[2] = f_path
                updt_cursor.updateRow(row)