[GIS] Calculate field using variables as fields gives ERROR 000539

arcpyerror-000539nameerror

When I calculate a field like this:

field_0="field_name0"
arcpy.CalculateField_management("Layer", field_0, '!field_name1! / !field_name2!', "PYTHON_9.3")

It works! The field "field_name0" in the attribute table is populated with the value calculated from fields "field_name1" and "field_name2".

But, if I use variables instead of field names:

field_0="field_name0"
field_1="!field_name1!"
field_2="!field_name2!"
arcpy.CalculateField_management("Layer", field_0, 'field_1 / field_2', "PYTHON_9.3")

I get this error:

Runtime error Traceback (most recent call last): File "",
line 3, in File "c:\program files
(x86)\arcgis\desktop10.2\arcpy\arcpy\management.py", line 3354, in
CalculateField raise e ExecuteError: ERROR 000539: Error running
expression: field_1/ field_2 Traceback (most recent call last):
File "", line 1, in NameError: name 'field_1' is
not defined Failed to execute (CalculateField).

I want to use loops later on, that's why I want it to work with variables, and not simply with direct field names.

Best Answer

Based on your variable, you just need to make sure variables and strings are not confused

field_1="!field_name1!"
field_2="!field_name2!"

arcpy.CalculateField_management("Layer", field_0, field_1 + " / " + field_2, "PYTHON_9.3")

note that if you have the strings as variables without the "!", it is nicer to use format()

field_1="field_name1"
field_2="field_name2"

arcpy.CalculateField_management("Layer", field_0, """!{}!/!{}!""".format(field_1,field_2), "PYTHON")
Related Question