I am trying to extract a raster through a particular shapefile.

   import arcpy
   from arcpy import env
   from arcpy.sa import *
   env.overwriteOutput = True

   #Set the current workspace
   env.workspace = ("C:\thesis\Forests Only Percent Treecover\2003 BSWM Forest")
   env.nodata = "MINIMUM"
   env.compression = "LZ77"

   #This is for extracting the forest areas of hansen percent treecover
   for raster in arcpy.ListRasters("*0E.tif", "TIFF"):
       print raster #checking the presence of raster
       outputRasterExtractbyMask = ExtractByMask(raster, "NAMRIA.shp")
       outputRasterExtractbyMask_Name = "forests_only"+raster

   print "Finish"

As I print the raster in arcpy.ListRasters to check the presence of raster, this error shows up:

 Traceback (most recent call last):
 File "C:\Users\brentiebark\Dropbox\Python Scripts and mxds\extractbymask.py", line 14, in <module>
 for raster in arcpy.ListRasters("*0E.tif", "TIFF"):
 TypeError: 'NoneType' object is not iterable

I double checked the directory, and my files are really there. Is there something wrong with my code?


Try replacing:

env.workspace = ("C:\thesis\Forests Only Percent Treecover\2003 BSWM Forest")


env.workspace = (r"C:\thesis\Forests Only Percent Treecover\2003 BSWM Forest")

The backslash is Python's escape character so when it appears in a DOS path you need to replace it with either a forward slash or double back slashes or just put an r for raw in front of the whole string.

There is also an error where:

for raster in arcpy.ListRasters("*0E.tif", "TIFF"):

should be:

for raster in arcpy.ListRasters("*0E.tif", "TIF"):
  • I've replaced it, but it just prints the "Finish" string and the extract by mask didn't execute. – brentiemapper Feb 8 '15 at 10:10
  • I typed print raster on the shell, but it says that it is not defined. – brentiemapper Feb 8 '15 at 10:13
  • That sounds like a new question so rather than change the existing one that is already answered would you normally be able to ask a new one, please? The need for one question per question is in the Tour but in this case I spotted an additional error so have "extended" my answer. – PolyGeo Feb 8 '15 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.