You should specify your expression type (eg, "PYTHON"
), but this will depend on which version of ArcGIS/arcpy you are using. "PYTHON"
for ArcMap is required, if you don't want it to default to "VB" (visual basic!). You can use VB if you wish, but it would be unusual to embed this into a Python (arcpy) script. (I think ArcGIS Pro defaults to "PYTHON3"
).
Additionally,But I think the main problem is that you have set your calc
string to include quotes at the beginning and enddouble quotation marks ("
) at the beginning and end within the string value itself when you do: calc = str('"%s"' %ID)
. This will result in a string value like "123"
INCLUDING the double quotes which cannot be converted to a number.
Try this instead:
arcpy.CalculateField_management(layer, fieldname, ID, "PYTHON", "")
ID
is already a string (has already been converted and cast to string earlier in the script), so no need to do it again, and it doesn't include the problematic extra quotation marks in the string value.
Now you can also delete the line: calc = str('"%s"' %ID)
As an aside, don't use str()
to cast strings to strings. It is redundant and also makes your code hard to read. For example, str(' = ')
is pointless. Just use ' = '
. Only use str()
if you need to convert something that is NOT a string into a string.