Last active
December 2, 2016 06:13
-
-
Save GISmd/81a49b47330ffef713e41d7d61c708fc to your computer and use it in GitHub Desktop.
A quick and dirty arcpy function that will iterate by features of a feature class and clip a target feature class; produces many output files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Needs some work. Needs error handling (empty outputs especially) and better | |
output naming logic. | |
""" | |
import arcpy, os | |
source_polys = r'path to shapefile to be clipped here' | |
clip_polys = r'path to shapefile whose features will be used for the clipping here' | |
def iterclipbyfeatures(source_polys, clip_polys, clip_id='FID', | |
output_prefix='', output_suffix=''): | |
"""Iteratively select by location using each feature in clippolys and | |
clipping the features within the source_polys. Will result in an output | |
for each feature class within the clippolys. | |
Places output in current working directory | |
Parameters: | |
source_polys : str | |
string of polygon feature class to extract features from | |
clippolys : str | |
string of polygon feature class for which each feature will be used | |
as the clipping features | |
clip_id : str | |
The field name containing unique IDs for which each output file | |
will be named. | |
output_prefix : str | |
self-explainatory | |
output_suffix : str | |
self-explanatory (I don't know it's spelled so I'll try two spellings | |
and maybe one of them is correct!) | |
""" | |
clip = arcpy.MakeFeatureLayer_management(clip_polys) | |
source = arcpy.MakeFeatureLayer_management(source_polys) | |
featurecount = arcpy.GetCount_management(clip) | |
with arcpy.da.SearchCursor(clip_polys, clip_id) as cursor: | |
for i, row in enumerate(cursor): | |
print 'Processing: {} of {}'.format(str(i+1), featurecount) | |
if type(row[0]) == int or type(row[0]) == float: | |
where = '"{}" = {}'.format(clip_id, str(row[0])) | |
else: | |
where = '"{}" = {}'.format(clip_id, "'{}'".format(row[0])) | |
print where | |
arcpy.SelectLayerByAttribute_management(clip, 'NEW_SELECTION', where) | |
curclip = arcpy.MakeFeatureLayer_management(clip) | |
arcpy.SelectLayerByLocation_management(source, 'HAVE_THEIR_CENTER_IN',curclip) | |
outputname = output_prefix + str(row[0]) + output_suffix + '.shp' | |
arcpy.FeatureClassToFeatureClass_conversion(source, os.getcwd(), outputname) | |
clippolyfcbyiterpolyfc(source_polys, clip_polys) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment