Let’s start with simple listing (i.e. all of your rasters are in one folder). Start the script with the basics.
import os
import arcpy
from arcpy import env
env.workspace = "wherever your stuff is"
Make sure you’re in the right place and Arc is “seeing” your files by just running arcpy.ListRasters() after you set the work space. For path names, though Arc may be everything Windows, remember this is Python, so forward slashes. Now, this is a small script that copies imagery into rasters. Use this if you need to convert images to GRID.
for raster in arcpy.ListRasters():
fileName,fileExtension = os.path.splitext(raster)
fileNameParts = fileName.split('_') #something useful?
arcpy.CopyRaster_management(raster,fileNameParts[0][8:11])
Now, let’s say I have a bunch of rasters in a bunch of sub-directories, and I need to do something to all of them. In this example, I’m assigning a value as “null.”
workspace = "wherever the files are located"
rasters = []
walk = arcpy.da.Walk(workspace, type="GRID")
for dirpath, dirnames, filenames in walk:
for filename in filenames:
rasters.append(os.path.join(dirpath, filename))
for raster in rasters:
fileNameParts = raster.split('\\')
outSetNull = SetNull(raster,raster,"VALUE < -2000")
outSetNull.save(fileNameParts[5] + fileNameParts[6])
Then, let’s say the sub-directories mean something (i.e. I want to do something by directory). In this case, all my images are grouped by month, and I want to perform calculations per month. First, let’s edit the list, so that now those month folders are the list items.
months = []
for dirpath, dirnames, filenames in walk:
for dir in dirnames:
months.append(os.path.join(dirpath,dir))
Then, a nested loop to first perform operations on all the rasters in each folder, then on each raster as needed.
for month in months:
fileNameParts = month.split('\\')
env.workspace = month
rasters = arcpy.ListRasters()
outCellStats = CellStatistics(rasters,"STD")
outCell = CellStatistics(rasters,"MEAN")
for raster in rasters:
difference = raster - outCell
SSG = arcpy.sa.Divide(difference,outCellStats)
SSG.save("output path" + fileNameParts[1] + raster)