I have been pulling out my hair trying to perform what should be a very simple field calculation. Below are code samples to show what works and what doesn't.
If I want to calculate "Main St and 1st Ave" into a text field, this works.
>>> arcpy.CalculateField_management(MyFC, "MyField", '"Main St and 1st Ave"')
<Result 'C:\\Test.gdb\\MyFC'>
Notice that the string is enclosed in double quotes, then further enclosed in single quotes. It took me a while to track down that syntax quirk.
However, I am iterating through a cursor, and my input string will be different for each iteration. I tried to set up the input for the calculatefield command accordingly.
>>> InputString = "'\"" + TextVar + "\"'"
>>> print InputString
'"Main St and 1st Ave"'
Now, since the value of InputString is exactly the same as what I entered in the first calculatefield command, there shouldn't even be a question as to whether or not it would give the same result, no? But this is what I get instead.
>>> arcpy.CalculateField_management(MyFC, "MyField", InputString)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\management.py", line 3354, in CalculateField
raise e
ExecuteError: ERROR 999999: Error executing function.
Syntax error
Failed to execute (CalculateField).
Hopefully it will turn out to be a very simple fix -- I would rather kick myself for not having seen something obvious than to continue to pull out my hair trying to figure out where I'm going wrong. Your advice and comments are greatly appreciated. Thank you.
Solved! Go to Solution.
Hi Stephen,
I find it difficult to format text variables when quotations are involved. One thing to try is to use the format option. Personally, I think it makes formatting strings much easier. For example, try the following:
TextVar = "Main St and 1st Ave" InputString = '"{0}"'.format(TextVar) arcpy.CalculateField_management(myFC, "MyField", InputString)
I'm curious why you wouldn't use an UpdateCursor—Help | ArcGIS for Desktop since you're already going through the records with a cursor. The syntax looks correct for your calculate field Calculate Field—Help | ArcGIS for Desktop.You may want to try arcpy.env.overwriteOutput = True. The data may be locked from the first calculate field.
Well, I'm not changing any of the data in the feature class upon which I was basing my cursor, so I don't really need an UpdateCursor for what I'm doing. Thanks, though.
Hi Stephen,
I find it difficult to format text variables when quotations are involved. One thing to try is to use the format option. Personally, I think it makes formatting strings much easier. For example, try the following:
TextVar = "Main St and 1st Ave" InputString = '"{0}"'.format(TextVar) arcpy.CalculateField_management(myFC, "MyField", InputString)
Bingo! That worked perfectly. Thanks for passing that along.