1

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?

4

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)
...
  • 1
    Thanks. The UpdateCursor worked fine when run in a script. Just had to remove the layer from ArcGIS Pro to avoid a 'could not acquire a lock' error. But thanks! – Theo F Oct 12 '18 at 13:22
  • It should also work with the layer added to the map and code pasted into the Python window. Did you have an Active edit session? I often add the layer to map, select some features and then use updatecursor in python window to only update selected features. – BERA Oct 12 '18 at 13:26
  • yeah I had been editing the attributes earlier within ArcGIS Pro. So there was a conflict when trying to edit it via an external script. I'm sure it'd have worked fine in the python console. – Theo F Oct 12 '18 at 13:30

Your Answer

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

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