Loop raster dataset in Python

8429
2
04-04-2013 04:57 PM
JessicaHeath
New Contributor
Hi,
I am very new to Python and I want to extract raster by mask for a number of images. I am attempting to write python code for this and incorporate a loop so it will process every raster image within the folder without me manually changing it. This is my code below but it does not work. From the #Loop through list of rasters sections i.e. rasters.reset() all the errors begin to occur. Can someone please help me fix this coding.


# Import system modules
import arcpy
from arcpy import env
from arcpy.sa import *

# Set environment settings
env.workspace = "J:\PhD\Vegetation\MODIS13Q1\MODIS_NDVI_z56"

# Set local variables
inRaster = "J:\MODIS"
inMaskData = "arcreproarea.shp"
outRaster = "J:\\MODIS"

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

# Get a list of the rasters in the workspace
    rasters = arcpy.ListRasters()
    rasters

# Loop through the list of rasters
    rasters.reset()
    raster = rasters.next()

while raster:
         # Set the outputname for each output to be the same as the input
        output = out_workspace + raster

       
        # Process: Extract by Mask
        arcpy.gp.ExtractByMask_sa(inRaster, inMaskData, outRaster)


        # Loop
        raster = rasters.next()


Thanks,
Jess
Tags (2)
0 Kudos
2 Replies
JessicaHeath
New Contributor
All good I have worked it out
0 Kudos
RaphaelR
Occasional Contributor II
Hi Jess,

i changed your code a bit (you´ll have to set the output path to where you want it), it should do what you want now:

# Import system modules
import arcpy
from arcpy import env
from arcpy.sa import *

# Set environment settings
env.workspace = r"e:\test"

# Set local variables
inMaskData = "rmask.shp"
outFolder = r"e:\test\masked"

# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")

# Get a list of the rasters in the workspace
rasters = arcpy.ListRasters()


# Loop through the list of rasters
for inRaster in rasters:
    # Set the outputname for each output to be the same as the input
    outRaster = outFolder + "\\" + inRaster


    # Process: Extract by Mask
    arcpy.gp.ExtractByMask_sa(inRaster, inMaskData, outRaster)
0 Kudos