There may be times when you need to retrieve the geometric definition of features in a feature class. ArcPy provides the ability to read this information through various objects.
In ArcPy, feature classes have associated geometry objects, including Polygon
, Polyline
, PointGeometry
, or MultiPoint
that you can access from your cursors. These objects refer to the shape
field in the table
attribute of a feature class. You can read the geometries of each feature in a feature class through these objects.
Polyline and polygon feature classes are composed of features containing multiple parts. You can use the partCount
property to return the number of parts per feature and then use getPart()
for each part in the feature to loop through each of the points and pull out the coordinate information. Point feature classes are composed of one PointGeometry
object per feature that contains the coordinate information for each point.
In this recipe, you will use the SearchCursor
and Polygon
objects to read the geometry of a polygon feature class.
Follow these steps to learn how to read the geometric information from each feature in a feature class:
C:ArcpyBookCh8ReadGeometry.py
.arcpy
module:import arcpy
SchoolDistricts
polygon feature class:infc = "c:/ArcpyBook/data/CityOfSanAntonio.gdb/SchoolDistricts"
SearchCursor
object with the input feature class, and return the ObjectID
and Shape
fields. The Shape
field contains the geometry for each feature. The cursor will be created inside a for
loop that we'll use to iterate all the features in the feature class:for row in arcpy.da.SearchCursor(infc, ["OID@", "SHAPE@"]): #Print the object id of each feature. # Print the current ID print("Feature {0}:".format(row[0])) partnum = 0
for
loop to loop through each part of the feature:# Step through each part of the feature for part in row[1]: # Print the part number print("Part {0}:".format(partnum))
for
loop to loop through each vertex in each part and print the X
and Y
coordinates:# Step through each vertex in the feature # for pnt in part: if pnt: # Print x,y coordinates of current point # print("{0}, {1}".format(pnt.X, pnt.Y)) else: # If pnt is None, this represents an interior ring # print("Interior Ring:") partnum += 1
C:ArcpyBookcodeCh8ReadGeometry.py
solution file.X
and Y
coordinates that define each part:Feature 1: Part 0: -98.492224986, 29.380866971 -98.489300049, 29.379610054 -98.486967023, 29.378995028 -98.48503096, 29.376808947 -98.481447988, 29.375624018 -98.478799041, 29.374304981
We initially created a SearchCursor
object to hold the contents of our feature class. After this, we looped through each row in the cursor by using a for
loop. For each row, we looped through all the parts of the geometry. Remember that polyline and polygon features are composed of two or more parts. For each part, we also return the points associated with each part and we print the X
and Y
coordinates of each point.