0

I have been trying this for hours and I know it should be easy but I can't make it work yet. I have a list of 50 rasters that I need to change the NoData to "0" values. I have the right arcpy function right but I can't get the loop to work yet (I'm a beginner) So far what I have is"

env.workspace = "My raster folder"
rasterList = arcpy.ListRasters("*.img")
print rasterList
#works
OutDir= "My output raster folder" + raster [0:7] + ".img"
#Here is my loop that won't work
for raster in rasterList:
    OutRaster = Con(IsNull(raster), 0, raster)
outCon.save(OutDir)
#this prodices only one raster out of the 50 rasters in the List.

I need to do the same iteration for all the 50 rasters and making sure that on each iteration both of the rasters entered in the Con function is the same each run, This is something like this:

Con(IsNull(raster1), 0, raster1)
Con(IsNull(raster2), 0, raster2)
Con(IsNull(raster50), 0, raster50)

Can someone help me?

  • Move outdir inside loop. Use arcpy.raster to convert strings to raster – FelixIP Oct 25 '14 at 1:21
1

as @FelixIP mentioned - you'll want to move the name of the output raster inside the loop (you could specify the directory outside the loop if you like, then append the output raster name) - you'll also need to change the name of the output variable to match that of the variable created with the Con statement and save it within the loop as well to save each raster - something like this (totally untested)...

import os #import in order to use os.path.join
...

OutDir= "My output raster folder"

for raster in rasterList:
    OutRaster = Con(IsNull(arcpy.Raster(raster)), 0, arcpy.Raster(raster))
    OutRaster.save(os.path.join(OutDir,raster [0:7] + ".img"))
|improve this answer|||||
  • Great , I just needed to modify the range for naming the output rasters [0:7] + "img" caused the process to interrupt after it found very similar named rasters. I used [0:-4] + ".img" to make sure the names kept the same and avoid naming conflicts. – Dan R Oct 26 '14 at 1:51
0

Thanks for the help!!! Now it is working, I just needed to use arcpy.raster, os.path.join and move the outdir inside of the loop. Here is the code that worked:

import os
env.workspace = "My directory with rasters"
OutDir= "My output directory"   
rasterList = arcpy.ListRasters("*.img")
print rasterList
for raster in rasterList:
    OutRaster = Con(IsNull(arcpy.Raster(raster)), 0, arcpy.Raster(raster))
    OutRaster.save(os.path.join(OutDir,raster [0:-4] + ".img")) 
print "Done with 50 rasters!"   
|improve this answer|||||

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.