Search code examples
pythonarcpy

Create for loop to process multiple rasters in a file using arcpy Clip management


I am trying to create a for loop to process (clip) multiple rasters that are in one file using arcpy Clip Management Tool. I first used model builder to create a script with the correct parameters in arcmap. I exported this script and then then updated to add in a loop to process multiple rasters in a folder. When attempting to run I'm getting back an error that None Type object not iterable. Here is error:
line 6, in <module>
for raster in rasterlist:
TypeError: 'NoneType' object is not iterable

import arcpy
texas_shp = "C:\\user\\Nicole\\data\\gis\\texas.shp"
tx__Name_ = "C:\\user\\Nicole\\date\\clippedimages\\tx_%Name%"
rasterlist = arcpy.ListRasters("C:\\user\\Nicole\\data\\gis\\imagestoclip")
for raster in rasterlist:
for i in range(30):
        arcpy.Clip_management(raster, "-8492199.91815014 -8492199.91793823 1914766.86774716 1213815.0683878", tx__Name_, texas_shp, "-2147483647", "NONE", "NO_MAINTAIN_EXTENT")
print arcpy.AddMessage(arcpy.GetMessages(0))

Solution

  • You can't export a ModelBuilder to Python and use it as it is.

    1. The dynamic %Name% notation used in ModelBuilder will not be recognoised in Python.

    2. You have to define the workspace of interest prior to running the ListRasters function (check its syntax here).

    3. Also, as mentioned by @abarnet, the for i in range(30): line is useless if you want to loop over all rasters in your workspace.

    4. If you use a shapefile as clipping geometry, it's not necessary to specify the rectangle parameter in the Clip tool.

    So your code should look like this:

    import arcpy, os
    texas_shp = "C:\\user\\Nicole\\data\\gis\\texas.shp"
    arcpy.env.workspace = "C:\\user\\Nicole\\data\\gis\\imagestoclip"
    
    rasterlist = arcpy.ListRasters()
    for raster in rasterlist:
        tx_name = os.path.join("C:\\user\\Nicole\\date\\clippedimages", "tx_" + raster)
        # If you want to maintain the clipping geometry:
        arcpy.Clip_management(raster, "#", tx_name, texas_shp, "-2147483647", "ClippingGeometry", "NO_MAINTAIN_EXTENT")
        # If you don't:
        arcpy.Clip_management(raster, "#", tx_name, texas_shp, "-2147483647", "NONE", "NO_MAINTAIN_EXTENT")
    

    If you have other arcpy related questions, you might want to ask them in gis.stackexchange.com, which is dedicated to GIS.