I am writing a script to loop through multiple folders and calculate mean of the raster of each folder's data sets and save it in same folder. Below script i am working, but its not producing the mean rasters for each year folder, after running the script its generating only name of "mean" raster in main folder, and overlapping it .
Below images showing the name of the raster in one folder, another folder the raster name is same, only year value is changed in different year.
here how to take the year value in name of mean raster (E.g. for 2001 folder, output mean raster name would be Mean_RAIN_2001.tiff)
Script:
import arcpy, os
from arcpy import env
arcpy.CheckOutExtension("Spatial")
arcpy.env.overwriteOutput = True
env.workspace = r"D:\Test"
outraster = env.workspace
walk = arcpy.da.Walk(env.workspace, topdown=True, datatype="RasterDataset")
for dirpath, dirnames, filenames in walk:
print dirpath
rasterList = arcpy.ListRasters("TIF")
print rasterList
for Rasters in rasterList:
rasMean = CellStatistics(Rasters,"MEAN", "DATA")
file_name_only = os.path.splitext(Rasters)[0]
tifname = file_name_only[-4:]
rasMean.save(os.path.join(outraster,'Mean_{0}.tif'.format(tifname)))
print rasMean
Printing statement: its printing only folder name,
D:\Test
[]
D:\Test2001円A
[]
D:\Test2002円A
[]
D:\Test2003円A
[]
D:\Test2004円A
[]
D:\Test2005円A
[]
D:\Test2006円A
[]
D:\Test2007円A
[]
D:\Test2008円A
[]
D:\Test2009円A
[]
1 Answer 1
I can see several things wrong with this script. Firstly you keep overwriting your output with this line:
rasMean.save(os.path.join(outraster,"mean.tif"))
The reasons for that is outraster
never changes as it comes from the environment settings which you set to d:\test. outraster
needs to change with each level that you are looping over (a concatenation of dirpath and dirnames).
I think it would be a good idea if you experiment with the walk() function and understand what it is generating as this is the source of your problem.
Secondly the tool CellStatistics takes as input a list of rasters, but your current code is building the list and calling the tool within your "for file in filenames" loop which is horribly inefficient. You need to build the list then feed that into the tool so all you need to do is remove the indentation from the 3 lines after the append call so they fall outside the loop.
try
/except
statements while testing.print
statements from running this code.