Select to view content in your preferred language

Adding multiple rasters together from a geodatabase - Getting AttributeError: 'str' object has no attribute 'write'

1076
2
10-30-2022 09:59 AM
Labels (2)
GriogairMorrison
New Contributor

I have written a script for a custom tool that gets all the rasters from a geodatabase and then adds them all together.

import arcpy
from arcpy import env
from arcpy.sa import *

workspace = arcpy.GetParameter(0)

SuitabilityRaster = arcpy.GetParameterAsText(1)

rasters = arcpy.ListRasters()

for inRaster in rasters:
             SuitabilityRaster = SuitabilityRaster + inRaster

SuitabilityRaster.write(workspace + "SuitabilityScoringGrid_Raster")

 

When I run the tool it gives the following error:  AttributeError: 'str' object has no attribute 'write'

 

Would be grateful if someone could help explain this and provide a solution? The 'SuitabilityRaster' begins as a constant raster surface with the value of 0 and then 'rasters' is a list of the rasters from the geodatabase that should be sequentially added to the 'SuitabilityRaster' within the for loop. 

Thanks.

0 Kudos
2 Replies
DanPatterson
MVP Esteemed Contributor

do you want to 'save' the raster? or `print` it?

in either event    ... (workspace + r"\SuitabilityScoringGrid_Raster")

would be needed


... sort of retired...
0 Kudos
Luke_Pinner
MVP Regular Contributor

You're telling arcpy to give you the parameter as text i.e. a str object when you use GetParameterAsText.

You need a Raster object.  Try using either:

 

#GetParameter
SuitabilityRaster = arcpy.GetParameter(1)

 

or

 

# arcpy.Raster
SuitabilityRaster = arcpy.Raster(arcpy.GetParameterAsText(1))

 

You'll also need to set the workspace:

 

arcpy.env.workspace = arcpy.GetParameter(0)

 

And possibly for convert inRaster to a Raster object as arcpy.ListRasters() returns strings

 

for inRaster in rasters:
    # you may need to convert inRaster to a Raster object
    # as arcpy.ListRasters() returns strings
    SuitabilityRaster = SuitabilityRaster + arcpy.Raster(inRaster)

 

So you'll end up with something like:

 

workspace = arcpy.GetParameterAsText(0)
SuitabilityRaster = arcpy.Raster(arcpy.GetParameterAsText(1))

rasters = arcpy.ListRasters()

for inRaster in rasters:
    SuitabilityRaster = SuitabilityRaster + arcpy.Raster(inRaster)

SuitabilityRaster.write(workspace + "SuitabilityScoringGrid_Raster")

 

 

0 Kudos