What I need to do:
- rename a field name of a table/feature class
- copy all values to the new field
So far I have done following code as @artwork21 suggests:
import sys
import traceback
import arcpy
from arcpy import env
## ARGUMENTS
# argv[1] = input table/feature class path
# argv[2] = input old field name
# argv[3] = input new field name
path = sys.argv[1]
oldFieldName = sys.argv[2]
newFieldName = sys.argv[3]
env.overwriteOutput = True
fields = arcpy.ListFields(path)
for field in fields:
if field.aliasName == oldFieldName:
if not oldFieldName == newFieldName:
fieldType = field.type
# Add new field
arcpy.AddField_management(path, newFieldName, fieldType)
#Calculates the new field based on old field values
arcpy.CalculateField_management(path, newFieldName, "!"+oldFieldName+"!", "PYTHON", "")
# Delete the old field (if necessary)
arcpy.DeleteField_management(path, oldFieldName)
How can I map field.type to AddField_management method's field type? And while the field is in a middle place, then field deleted from middle and added to the last. That does not looks like as if field name is renamed.
Is there any better solution that help me to do these things?
old_fielda variable name or the actual name of the old field? If it's a variable name you need to use string formatting or concatenation to wrap the value of the variable with the brackets (VB parser) or exclamation points (Python parser). – blah238 Feb 21 '13 at 01:46arcpy.CalculateField_management(layer, new_field, "!old_field!", "PYTHON", "").Doesn't it what you tell me to do? – Emi Feb 21 '13 at 13:05field.aliasName == oldFieldName. A field alias name is allowed (really, intended) to be different from its name. Did you meanfield.name? – blah238 Feb 22 '13 at 06:39