Skip to content

Instantly share code, notes, and snippets.

@NPS-ARCN-CAKN
Created April 13, 2015 20:44
Show Gist options
  • Save NPS-ARCN-CAKN/cd637754d5e4dfe73588 to your computer and use it in GitHub Desktop.
Save NPS-ARCN-CAKN/cd637754d5e4dfe73588 to your computer and use it in GitHub Desktop.
Python: Open a shapefile and loop through the records
# basic example of opening a shapefile and then looping through the records and outputting them to console
import arcpy
# Supply a path to the shapefile
fc = "C:/Temp/MurphyProjected.shp"
# we'll need to create a searchcursor a little further on to access the records in the layer. the cursor has a fields parameter
# we could just submit a * to gather all columns except that we need the Shape column returned as a token, e.g. Shape@,
# so we have to submit all the columns as a list with Shape changed to the Shape@ token that will allow us to get at geometry info.
# The easiest way to do this is to loop through the column names and load them into a list making our edits as needed
fieldsList = arcpy.ListFields(fc) #get the fields
fields = [] # create an empty list
# loop through the fields and add the columns to the list, change the Shape column (containing geometry) into a token,
for field in fieldsList:
if field.name == "Shape":
fields.append("Shape@")
else:
fields.append(field.name)
# just for fun print out the fields
i = 0
print 'Fields in ' + fc
for field in fieldsList:
print field.name + " = row[" + str(i) + "]"
i = i + 1
# get the transect data into a cursor so we can translate it into sql to insert into the sheep sql server database
# loop through the cursor and save fields as variables to be used later in insert queries
# spatial coordinate system
epsg = 4326 # WGS84
sr = arcpy.SpatialReference(epsg)
cursor = arcpy.da.SearchCursor(fc,fields,"",sr)
for row in cursor:
FID = row[0]
Shape = row[1]
CODE = row[2]
Geog = "geography::STGeomFromText('" + Shape.WKT + "', " + str(epsg) + ")"
#print str(CODE) + ": " + Geog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment