I'm a newcomer to Python scripting and I'm having what's seemingly a very simple problem but one that's stumped me enough to send me posting to these forums for the first time.

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, which it surely must be. I'm using ArcGIS 10.0 btw. Thanks for your help!


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. Have you tried adding withhole = None at the end of the loop, or after the loop, telling arcpy that it now must write the raster?

| improve this answer | |
  • Brilliant, thank you sir, you are a lifesaver. I had a feeling there'd be a simple solution, but I don't think I would've thought to simply assign something unrelated to the variable at the end. I suppose it kind of makes sense, though I don't think I've seen it do this w/ saving not in a loop. Good to know. – user14175 Jan 12 '13 at 19:25

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.