I am working on a Python script using Arcpy. It creates a shape file, and then adds fields to it with names coming from user input. From the string the user has entered I need to produce a valid field name. I thought arcpy.ValidateFieldName()
would accomplish this. However, I am having problems. Consider the code below:
#Create a new shapefile.
arcpy.CreateFeatureclass_management(r"C:\path\to\file", "shape.shp")
#Validate the fieldname.
name = arcpy.ValidateFieldName("0FIELD", "shape")
#Add the field
arcpy.AddField_management("shape", name, "TEXT")
Even though the field name has been validated, it throws an error:
Runtime error Traceback (most recent call last):
File "", line 1, in
File "C:\script.py", line 8, in
arcpy.AddField_management("shape", name, "TEXT")
File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\management.py", line 3200, in AddField
raise e ExecuteError: ERROR 000310: The Field name must not start with a number
The function corrects other unallowed character (such as replacing spaces with underscores, and capping the string at 10 characters), but it misses to do something about the first character being a number even though that is not allowed in shape file field names.
Is this a bug, or am I using arcpy.ValidateFieldName()
wrongly? Is there some other function I should use? Or will I have to write one myself? What should that one look like?
EDIT 1: Replacing the second argument to ValidateFieldName
with the full path and filename of the shape file does not help.
EDIT 2: When adding a field called 0FIELD
from ArcCatalog it works fine. So rather than this being a problem with the validation, it seems that AddField_management
disallows field names starting with a number, even though it shouldn't.
I've been in contact with ESRI support, and according to them it is an issue with ArcMap 10.2 that is fixed in 10.3. Have not been able to verify that, however.