2

ArcGIS Pro 2.3

I want to create a standalone script which runs outside of ArcGIS Pro (for automation purposes), which selects features (with blank attributes) in a feature class and runs calculate field on those selections.

The code below doesn't work. It updates all fields, not the selected ones.

import arcpy
arcpy.management.SelectLayerByAttribute(r"C:\Automation\Categories\Coal\Coal_automation.gdb\CLAIMS", "NEW_SELECTION", "Claim_Spend_in_£ = ''", None)

arcpy.management.CalculateField(r"C:\Automation\Categories\Coal\Coal_automation.gdb\CLAIMS", "Claim_Spend_in_£", '"Unrecorded"', "PYTHON3", None)
print ("Done")

How can I write the code to run calculate field on a selection?

1 Answer 1

7

Use da.UpdateCursor instead of Field Calculator, it is more versatile and easier to use and you can pass the sql statement to only update "selected" rows:

import arcpy

fc = r"C:\Automation\Categories\Coal\Coal_automation.gdb\CLAIMS"
fieldname = "Claim_Spend_in_£"

sql = """{0} = ''""".format(arcpy.AddFieldDelimiters(fc,fieldname))

with arcpy.da.UpdateCursor(fc,fieldname,sql) as cursor:
    for row in cursor:
        row[0] = 'Unrecorded'
        cursor.updateRow(row)

If you want to use Field Calculator on a layer:

A selection cant be made on a feature class, it has to be a layer. You can create a layer with MakeFeatureLayer then pass 'lyr' to calculate field:

sql = """{0} = ''""".format(arcpy.AddFieldDelimiters(fc,fieldname))
arcpy.MakeFeatureLayer_management(in_features=fc, out_layer='lyr', 
                                 where_clause=sql)
...
0

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.