[GIS] Concatenating text and string in Field Calculator expression (python)

arcgis-desktoparcmaparcpyfield-calculator

I'm trying to copy an attribute value from one field to another (sum of raster values), but I'm having issues in writing a functioning expression for a Calculate Field script. I'm adding a field called SUM and trying to copy the value from the field "SUM_" + filename[0:-4]. I have multiple files I am trying to do this on and the field names are different in each, which is why it is being written in this manner.

Here's the code I have so far:

for table in arcpy.ListTables():
    arcpy.AddField_management(table, "SUM", "DOUBLE")
    expression = ["SUM_" + str(filename[0:-4])]
    arcpy.CalculateField_management(table, "SUM", expression, "VB")  

This doesn't work as I receive the following error:

File "C:\Users\kellyj\Desktop\Projects\CostAnalysis\Route_Cost_Analysis.py", line 82, in <module>
    arcpy.CalculateField_management(table, "SUM", expressionvalue, "VB")
File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\management.py", line 3354, in CalculateField
    raise e
RuntimeError: Object: Error in executing tool

Any thoughts as to how I can fix this?

Best Answer

You have to have a square bracket surrounding the "SUM_" thing

Trying change

expression = ["SUM_" + str(filename[0:-4])]

to

expression = "[SUM_{0}]".format(str(filename[0:-4]))
Related Question