0

I'm tyring to write a script the allow me to select a layer by location, then calculate a field of the selected feature. But I'm having issue with CalculateField_management.

Here part of the script:

farmsArea = r"pathFeature" 
enclaves = r"pathFeature"

# Select  by location -->  farms within Enclaves 
arcpy.SelectLayerByLocation_management(farmsArea, 'INTERSECT', enclaves, "", 'NEW_SELECTION')

# Calculate field "within enclaves = (here i have an issue, the name "yes" is not defined)
arcpy.CalculateField_management(farmsArea, 'within_enc', 'yes', 'PYTHON3')

# Switch selection and calculate "within enclaves = no"
arcpy.SelectLayerByAttribute_management(farmsArea, 'SWITCH_SELECTION')
arcpy.CalculateField_management(farmsArea, "'within_enc'", "no" )

# Clear selection
arcpy.SelectLayerByAttribute_management(farmsArea, 'CLEAR_SELECTION')

As error I have row 8 "name 'yes' is not defined"

1
  • try adding quotes around it to make it a string e.g. '"yes"'
    – SMiller
    Jun 15, 2020 at 19:04

1 Answer 1

2

Arcpy doesn't allow you to use "Calculate field" tool to do a calculation on a subset of features. Once you fix the double quotes error mentioned by smiller you will see that all rows in your field will be updated.

What you need to do is use arcpy's update cursor. In fact, there is another forum posting about this same problem.

Link to other stack exchange code

1
  • 2
    You can do the calculation on a subset of features in a feature layer (not the initial path to the file; see the link above). Especially since you are trying to test two conditions and update the field for either condition, the da.UpdateCursor would work best.
    – SMiller
    Jun 15, 2020 at 21:05

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