Monday, 3 April 2017

arcpy - Bulk field renaming in file geodatabase?



I have a file geodatabase with several hundred feature classes in it.


Some feature classes have a field that got named incorrectly, and it got named "SCHEMA_FEATURECLASS_ENTITY" instead of just ENTITY. Consequently, their final destination (Oracle) complains about the very long field names.


I'd like to rename those fields to have their proper short name. I did find Changing feature class and field aliases in bulk using ArcPy? but (from what I understand) renaming a field is an add-copy-delete operation rather than just setting a property.


Has anyone got a quick-and-dirty method for doing a bulk rename? I have ArcCatalog 9.3.1 but NOT Visual Studio (client environment...).



Answer



You can use a Python script to do the heavy work for ya:


Check this out and adapt it to your needs. Needless to say, this is not tested, and don't use it on production data WITHOUT MAKING A BACKUP FIRST.



import arcgisscripting

gp = arcgisscripting.create(9.3)

gp.Workspace = "path_to_your_geodatabase"

# you can use absolute path to this function
gp.AddToolbox("management")

featureClasses = gp.ListFeatureClasses("*","ALL")


for featureClass in featureClasses:
fields = featureClass.ListFields("*","ALL")

for field in fields:

# do not duplicate oid and geometry fields
if field.Type == "OID" or field.Type == "Geometry":
continue


# lets refactor our field name
# this transforms A_B_C into C
fieldNames = field.Name.split("_")
del(fieldNames[0:1])

# add a new field using the same properties as the original
# field
gp.AddField(featureClass,fieldNames[0],field.Type)

# calculate the values of the new field

# set it to be equal to the old field
gp.CalculateField(featureClass,fieldNames[0],field)

# delete the old fields
gp.DeleteField(featureClass,field)

I did not tested it, so test it and let me know if it works. If you need to change the name of the field in a different way, just alter the refactor part.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...