Select to view content in your preferred language

Successive commands within a for loop in arcpy

691
3
Jump to solution
12-05-2020 07:11 AM
CamiSunley
Emerging Contributor

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.

0 Kudos
1 Solution

Accepted Solutions
DavidPike
MVP Frequent 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
DavidPike
MVP Frequent 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)
CamiSunley
Emerging Contributor

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)))

 

 

0 Kudos
DavidPike
MVP Frequent 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)