Recursive Listing Using ArcPy

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?  

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")[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:  

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 =,outCellStats)  
 "output path" + fileNameParts[1] + raster) 

Leave a Reply

Your email address will not be published. Required fields are marked *