Clip Raster based on Shp with same name

07-18-2016 08:49 AM
Regular Contributor

Does anyone know of a script that will iterate rasters and grab its associated shapefile (same name as raster) and clip using the two inputs?

Basically I have:

Raster1, Shapefile1

Raster2, Shapefile2

Raster3, Shapefile3


Raster250, Shapefile250

I've seen some basic clip scripts that use ListRasters to iterate through rasters.

Batch Clip in ModelBuilder of ArcGIS for Desktop? - Geographic Information Systems Stack Exchange

I figured this most likely can't be done in Model Builder or can it?



0 Kudos
4 Replies
Regular Contributor

I wrote a small script that on first test runs seems to accomplish what I need.  I will run a few more tests and post the script.


0 Kudos
Regular Contributor

Here's my script.  I converted it to a toolbox.  To import to a toolbox, save it as a file (example: [make sure the .py is on the file name]) Right click a toolbox and Add Script, then set 3 parameters 1) Input GRIDs 2) Input Polygons 3) Output Directory.  Set them all as workspaces. This script assumes your polygons are named exactly the same as the grid files you will be clipping.  If your output directory is a folder, your file names can't be longer than 13 characters.  It's best to output to a geodatabase.

import arcpy

# Set the current workspace
arcpy.env.workspace = arcpy.GetParameterAsText(0) #"D:\\Test2\\Grids.gdb"

#Polygon Shapefiles Workspace
clipFeatures = arcpy.GetParameterAsText(1) #"D:\\Test2\\Shps\\"

#Output Directory
outDirectory = arcpy.GetParameterAsText(2) #"C:\\Users\\sgraf\\Documents\\ArcGISData\\Test2\\Outs.gdb\\"

# Get and print a list of GRIDs from the workspace
rasters = arcpy.ListRasters("*", "GRID")

for raster in rasters:

    arcpy.AddMessage("Clipping " + raster + " with " + raster + ".shp")

    desc = arcpy.Describe(clipFeatures + "\\" + raster + ".shp")  
    extent = desc.extent  
    raster, str(extent), outDirectory + "\\" + raster, clipFeatures + "\\" + raster + ".shp", "#", "ClippingGeometry", "NO_MAINTAIN_EXTENT")


0 Kudos
MVP Esteemed Contributor

Do you want me to convert this series of posts to a discussion?  There is little point asking and answering since you are the only one that contributed.  Let me know

Regular Contributor

Go for it, Thanks!

0 Kudos