[GIS] rename feature layer fields

arcpyfields-attributes

Guys and gals could you please provide me with a sample code as to how to rename a field name in a Feature Layer or Table. I've been trying to use the FieldInfo object to do so over the last couple of days but it's not happening for me.

Best Answer

What this example code does is to add two NEW fields ("NAME_CITY"; "NAME_REGION") into your fieldinfo with desired new field names instead of just renaming the ORIGINAL field ("NAME_1"; "RegionNames").

After you renamed your fields you need to copy your table view/feature layer into a new table/feature class and that will be your output with renamed fields in it.

import arcpy
import os
from arcpy import env
env.overwriteOutput = True

inputFeatureClass=r"C:/Desktop/Cities/Cities.gdb/USA_Cities"

#get fields from your input feature class
fields= arcpy.ListFields(inputFeatureClass)

# Create a fieldinfo objects
fieldinfo = arcpy.FieldInfo()

# Iterate through the fields and set them to fieldinfo
for field in fields:
    if field.name == "NAME_1":
        fieldinfo.addField(field.name, "NAME_CITY", "VISIBLE", "")
    elif field.name == "RegionNames": 
        fieldinfo.addField(field.name, "NAME_REGION", "VISIBLE", "")

# The created table view will have fields as set in fieldinfo objects
arcpy.MakeTableView_management(inputFeatureClass, "temp_Table_View", "", "", fieldinfo)

# Write the table view to a new table
arcpy.CopyRows_management("temp_Table_View", "C:/Desktop/Cities/Cities.gdb/City_Table")