0

I have multiple rasters that I want to get the mean of the all the cells. This is what I have:

env.workspace = r"C:\Users\pyb609\Desktop\Updated 
Files\GIS\Dark\Shapefiles\15M"
outfile = open(r"C:\Users\pyb609\Desktop\UpdatedFiles\GIS\Dark\Shapefiles\15M\15M_Mean.txt", 'w')

#Check out the Arcgis Spatial Anaylst extension licence
arcpy.CheckOutExtension("Spatial")

# Get a list of Rasters
rasterList = arcpy.ListDatasets("*","Raster")    

for inRaster in rasterList:
    # just to view progress
    print inRaster
    outfile.write(inRaster)

    Mean =arcpy.GetRasterProperties_management(inRaster, "MEAN")
    textinfo =(inRaster, Mean)
    textstring =str(textinfo)
    outfile.write(textstring)
    outfile.close()

It gives me the first file but then I get an error:

Traceback (most recent call last): 
File "C:\Users\pyb609\Desktop\Updated Files\GIS\Dark\MeanRaster.py", line 26, in <module> outfile.write(inRaster) 

ValueError: I/O operation on closed file
2

You are closing your outfile in the loop iteration. Either close it after the loop or use a with statement. Also, you should use .getOutput() to get the actual value from the GetRasterProperties tool.

Something like:

env.workspace = r"C:\Users\pyb609\Desktop\Updated Files\GIS\Dark\Shapefiles\15M"

#Check out the Arcgis Spatial Analyst extension licence
arcpy.CheckOutExtension("Spatial")

# Get a list of Rasters
rasterList = arcpy.ListDatasets("*","Raster")    

with open(r"C:\Users\pyb609\Desktop\UpdatedFiles\GIS\Dark\Shapefiles\15M\15M_Mean.txt", 'w') as outfile:

    for inRaster in rasterList:
        # just to view progress
        print inRaster

        Mean =arcpy.GetRasterProperties_management(inRaster, "MEAN").getOutput(0)

        textinfo = (inRaster, Mean)
        textstring = '%s, %s\n' % textinfo
        outfile.write(textstring)

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.