ArcPy Field Renaming – How to Rename Fields in ArcGIS 10.0

arcgis-10.0arcpyfields-attributes

What I need to do:

  1. rename a field name of a table/feature class
  2. 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?

Best Answer

Try this using a combination of Add Field, Calculate Field, and Delete Field arcpy tools:

if fieldInfo.getFieldName(index) == "status":
    arcpy.AddField_management(layer, "stat", "TEXT", "", "", "50", "",        "NULLABLE", "NON_REQUIRED", "")                     
    arcpy.CalculateField_management(layer, "stat", "!status!", "PYTHON_9.3", "")
    arcpy.DeleteField_management(layer, "status")