[GIS] Calculating a z value in python

arcgis-10.2arcpyfield-calculatorpython

I have some contours where the z value is stored in the geometry and I want to display it as an attribute. I want to include this in a python script.

I have an expression which does this in python field calculator:

!Shape!.firstpoint.z

This works perfectly, but when I include it in my script:

arcpy.CalculateField_management( shapefile , "VALUE" , "!Shape!.firstpoint.z", "PYTHON")

this does not work, which surprises me because I thought that the Calulate Field was exactly the same as field calcultor, but accessed through arcpy.

The error is that its a string, so has no z attribute: " File "", line 1, in
AttributeError: 'str' object has no attribute 'z"

So I've tried:

arcpy.CalculateField_management( shapefile , "VALUE" , "!Shape.firstpoint.z!", "PYTHON")

and that tells me that "firstpoint.z" isnt an attribute of shape

I then tried:

arcpy.CalculateField_management( shapefile , "VALUE" , "!Shape.firstpoint!.z", "PYTHON")

And that seemed to view the first point as a unicode rather than a point. "File "", line 1, in AttributeError: 'unicode' object has no attribute 'z'"

It seems that my problem is getting it to view firstpoint as a point, but I'm not not why this is.

Best Answer

Expression type needs to be PYTHON_9.3

This code worked for me:

from arcpy import *

fc = r"C:\test\test.gdb\test"
fld = "testfld"

shapeFldName = Describe (fc).shapeFieldName

CalculateField_management (fc,
                           fld,
                           "!{}!.firstPoint.Z".format (shapeFldName),
                           "PYTHON_9.3")

Happy pythoning!

Related Question