# Name: CalculateField_Centroids.py
# Description: Use CalculateField to assign centroid values to new fields
# Import system modules
import arcpy
from arcpy import env
try:
# Set environment settings
env.workspace = "C:/RUTA_CARPETA/"
# Set local variables
inFeatures = "NOMBRE_DEL.shp"
fieldName1 = "xCentroid"
fieldName2 = "yCentroid"
fieldPrecision = 18
fieldScale = 11
# Expressions are calculated using the Shape Field's geometry property
expression1 = "float(!SHAPE.CENTROID!.split()[0])"
expression2 = "float(!SHAPE.CENTROID!.split()[1])"
# Execute AddField
arcpy.AddField_management(inFeatures, fieldName1, "DOUBLE",
fieldPrecision, fieldScale)
arcpy.AddField_management(inFeatures, fieldName2, "DOUBLE",
fieldPrecision, fieldScale)
# Execute CalculateField
arcpy.CalculateField_management(inFeatures, fieldName1, expression1,
"PYTHON")
arcpy.CalculateField_management(inFeatures, fieldName2, expression2,
"PYTHON")
except Exception, e:
# If an error occurred, print line number and error message
import traceback, sys
tb = sys.exc_info()[2]
print "Line %i" % tb.tb_lineno
print e.message
No olvidar reemplazar la ruta de la carpeta y nombre del shapefile.