GEOG 485:
GIS Programming and Automation

Lesson 4 Practice Exercise A Solution

PrintPrint

Here's one way you could approach Lesson 4 Practice Exercise A with comments to explain what is going on. If you have a different or more efficient solution, please share in the forums.  If you find a more efficient way to code a solution, please share it through the discussion forums.

# Reads coordinates from a text file and writes a polygon
 
import arcpy
import csv
 
shapefile = "C:\\data\\Geog485\\MysteryState.shp"
pointFilePath = "C:\\data\\Geog485\\MysteryStatePoints.txt"
spatialRef = arcpy.Describe(shapefile).spatialReference
 
# Open the file and read the first (and only) line
pointFile = open(pointFilePath, "r")
csvReader = csv.reader(pointFile)
 
# This Array object will hold a clockwise "ring" of Point
#  objects, thereby making a polygon.
polygonArray = arcpy.Array()
 
# Loop through each coordinate pair and make a Point object
for coords in csvReader:
    
    # Create a point, assigning the X and Y values from your list    
    currentPoint = arcpy.Point(coords[0],coords[1])
 
    # Add the newly-created Point to your Array    
    polygonArray.add(currentPoint)
 
# Create a Polygon from your Array
polygon = arcpy.Polygon(polygonArray, spatialRef)
 
# Create an insert cursor and apply the Polygon to a new row
with arcpy.da.InsertCursor(shapefile, ("SHAPE@",)) as cursor:
    cursor.insertRow((polygon,))

Below is a video offering some line-by-line commentary on the structure of this solution: