I'm a newcomer to Python scripting.

I'm using a for loop to save rasters to a specified folder. The loop executes perfectly, but the last iteration of the loop invariably produces an empty raster with no spatial reference. So, iteration 1 will be an empty raster until I run iteration 2, at which point the product of iteration 1 mysteriously transforms into what I want, & so on w/ iterations 2 & 3, etc. In keeping w/ this pattern, the last raster created by the loop remains empty and unprojected.

Code is as follows ("costsurf" & "distDirString" are defined in an earlier part of the script):

for Num in Nums:
 focal = arcpy.sa.SetNull("Corr","Corr","VALUE <> " + str(Num))
 costDist = arcpy.sa.CostDistance(focal,costsurf)
 withhole = arcpy.sa.SetNull(~ arcpy.sa.IsNull(focal),costDist)
 withhole.save(os.path.join(distDirString,"dist_%s.img" %Num))

It's supposed to pull out a chunk of the raster "Corr" with cell values Num by setting all else to NoData, run the Cost Distance tool on it, then poke a hole in the result where the source cells are. I have no idea how to think about what's failing here, since the loop does exactly what I want it to, but only if it's not the last iteration to be run.

It seems to behave itself if I get rid of the ".img" and save them as GRIDs but only sometimes, and I'd really rather stick to .img if at all possible.

I'm using ArcMap 10.0.


I seem to recall working with ArcPy that some optimizations are at work, such as not writing data to disk when it may be altered later.

Try adding withhole = None at the end of the loop, or after the loop, telling arcpy that it now must write the raster.


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.