Successive commands within a for loop in arcpy

176
3
Jump to solution
12-05-2020 07:11 AM
New Contributor II

Hello, everyone !

I have a list of rasters ('intlist') and for each of them I want to execute succesive commands ('Minus' and 'Con') within a for loop trying to avoid the middle results load and keep only the output rasters from the last command within the loop. I tried the code below but it doesn't return right results, so I would like to ask if there is something that can fix this. 

for i in intlist:
enVr = Minus(i, 260)
outCon = Con(enVr, enVr, 0, "Value >= 0")
name = "C:/MSc_thesis/int/" + "en{}".format(i)
outCon.save(name)

Thank you.

Reply
0 Kudos
1 Solution

Accepted Solutions
MVP Regular Contributor

isn't the return value of ListRasters a string? i.e. intlist is a list of string names of the raster, not Raster Objects.

I'd say to cast the raster into an object with ras_object = arcpy.Raster(i)

i may even just be the name and not the path, whereby you would have to get the raster path with something like path = os.path.join(arcpy.env.workspace, i)

ras_object = arcpy.Raster(path)

View solution in original post

3 Replies
MVP Regular Contributor

can you post the full code?

A quick first guess would be that theres no format specified in the string, theres also no need to combine + with .format

 

name = "C:/MSc_thesis/int/en{}.tif".format(i)
New Contributor II

Here is another option of saving the output.. The names are saved correctly, but the output it's not right concerning the calculations as there are still Values <0. 

from arcpy import env

from arcpy import env

from arcpy.sa import *

import os

arcpy.env.workspace = "C:/MSc_thesis"

intlist  = arcpy.ListRasters("*", "TIF")

f = 260

for i in intlist:

     enVr = Minus(i, f)                              

     outCon = Con(enVr, enVr, 0, "Value >= 0")

     outCon.save(os.path.join(arcpy.env.workspace,"en" + str(i)))

 

 

Reply
0 Kudos
MVP Regular Contributor

isn't the return value of ListRasters a string? i.e. intlist is a list of string names of the raster, not Raster Objects.

I'd say to cast the raster into an object with ras_object = arcpy.Raster(i)

i may even just be the name and not the path, whereby you would have to get the raster path with something like path = os.path.join(arcpy.env.workspace, i)

ras_object = arcpy.Raster(path)

View solution in original post