Skip to content

Instantly share code, notes, and snippets.

@pmacMaps
Created June 21, 2019 15:35
Show Gist options
  • Save pmacMaps/4207a6b32f91c836ee3b6b2743d2c71a to your computer and use it in GitHub Desktop.
Save pmacMaps/4207a6b32f91c836ee3b6b2743d2c71a to your computer and use it in GitHub Desktop.
# ---------------------------------------------------------------------------
# Name: Loop Through Layer "A" and Clip Features from Layer "B"
#
# Author: Patrick McKinney, Cumberland County GIS (pmckinney@ccpa.net or pnmcartography@gmail.com)
#
# Created on: 6/21/2019
#
# Description: This sample script provides a template for how to loop through a layer (A) and clip features
# from another layer (B) based upon each record in layer A.
#
# As an example, you may want to clip a hydrography layer by each County in a state. This script
# automates what would otherwise be a long manual process.
#
# Disclaimer: CUMBERLAND COUNTY ASSUMES NO LIABILITY ARISING FROM USE OF THESE MAPS OR DATA. THE MAPS AND DATA ARE PROVIDED WITHOUT
# WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE.
# Furthermore, Cumberland County assumes no liability for any errors, omissions, or inaccuracies in the information provided regardless
# of the cause of such, or for any decision made, action taken, or action not taken by the user in reliance upon any maps or data provided
# herein. The user assumes the risk that the information may not be accurate.
# ---------------------------------------------------------------------------
# Import system modules
import arcpy, sys, os
# Run geoprocessing tool.
# If there is an error with the tool, it will break and run the code within the except statement
try:
# location where you want the clipped layers to be stored
out_gdb = r'C:\GIS\Clipped\Output.gdb'
# Geodatabase storing layers that participate in clip
# you can also reference the full path to each layer when you construct its variable
parent_gdb = r'G:\Data\Geodata.gdb'
# hydrography (streams) layer
streams_fc = os.path.join(parent_gdb, 'Streams_Polyline')
# counties layer
counties = os.path.join(parent_gdb, 'Counties')
# fields from Counties layer to use in cursor
county_fields = ['OBJECTID','NAME']
# create feature layer for Counties so you can clip by each record within cursor
arcpy.MakeFeatureLayer_management(counties,'County')
# print statement to console
print 'Created feature layer for Counties layer\n'
# Create Search Cursor for Counties
# print statement to console
print '\nCreating search cursor on Counties layer'
# create search cursor
with arcpy.da.SearchCursor(counties, county_fields) as cursor:
# loop through each record in Counties layer
for row in cursor:
# where clause
where_clause = "OBJECTID = {}".format(row[0])
# select the current record from the Counties layer using OBJECTID
arcpy.SelectLayerByAttribute_management('County', 'NEW_SELECTION', where_clause)
# clip streams by county
arcpy.Clip_analysis(streams_fc, 'County', os.path.join(out_gdb, '{}_Streams'.format(row[1])))
# print statement to console
print 'Clipped Streams layer for {}\n'.format(row[1])
# end for
# end with cursor
# delete cursor
del cursor
# If an error occurs running geoprocessing tool(s) capture error and write message
# handle error outside of Python system
except EnvironmentError as e:
tbE = sys.exc_info()[2]
# add the line number the error occured to the log message
print "Failed at Line {}\n".format(tbE.tb_lineno)
# add the error message to the log message
print "Error: {}\n".format(str(e))
# handle exception error
except Exception as e:
# Store information about the error
tbE = sys.exc_info()[2]
# add the line number the error occured to the log message
print "Failed at Line {}\n".format(tbE.tb_lineno)
# add the error message to the log message
print "Error: {}\n".format(e.message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment