How do I ask a “for loop” to operate on groups of three files folder (e.x. files A, B, C), then files B, C, D, and then files C, D, E, and so on?
I have a folder full of rasters (.tif): RasterA.tif, RasterB.tif, RasterC.tif, RasterD.tif…and so on. I’ve got a python script that can run the batch conditional test I want. However, it only runs through one raster at a time, and I’d like it to run through multiple.
I think it’s easier to show via code. Please see below.
# Omitted the top part of the script for readability. # I have all the imports (arcpy and os), set the environment, set overwrite, set cell size # Please let me know if I need to add this top part back in to the question and I will rasters = arcpy.ListRasters("*", "ALL") for raster in rasters: inRas = Raster(raster) #pulls the first raster (ex. Raster A) inRas2 = Raster(raster) # Right now I know this means inRas and inRas2 are the same thing. # What I'd like to do is have inRas2 be the next raster "in line" (ex. Raster B) inRas3 = Raster(raster) # Same deal as above, would like it to be Raster C # The CON test itself output = arcpy.sa.Con(inRas >= 25, 1, 0) + arcpy.sa.Con(inRas2 >= 20, 1, 0) + arcpy.sa.Con(inRas3 >= 15, 1, 0) # My output raster needs to be identified by the first file in the group # This part runs fine, can ignore in context of question RasName, RasExt = os.path.splitext(raster) output.save(outWorkspace + RasName + ".tif")
The fixed script is below. Everything ran without problem.
# Get a list of Rasters rasters = arcpy.ListRasters("*", "ALL") # set it so can pull group of rasters with indexing n = len(rasters) # run the con test on batch, in groups of 3 for i in range(2,n): rasterA = Raster(rasters[i-2]) rasterB = Raster(rasters[i-1]) rasterC = Raster(rasters[i]) output = arcpy.sa.Con(rasterA >= 25, 1, 0) + arcpy.sa.Con(rasterB >= 20, 1, 0) + arcpy.sa.Con(rasterC >= 15, 1, 0) RasName, RasExt = os.path.splitext(rasters[i-2]) output.save(outWorkspace + RasName + ".tif") # I have it print just to make sure naming files goes right print RasName print RasExt print "Done"