0

I have a series of files named as 'rawfile200101', 'rawfiles200102',...,'rawfile201104'. I want to do ZonalStatisticsAsTable for each of them with names corresponding to the time of the raw files, such as 'newfile200101', 'newfiles200102',...,'newfile201104'. I know how to script it for individal file, but I am trying to do it in batch. I wrote the following codes for four files, it is always shown error that "I:/rawfile%list%.tif" does not exist.

import arcpy
from arcpy import env
from arcpy.sa import *
arcpy.CheckOutExtension("Spatial")

yrmn = ['200101', '200102', '200103', '200104']

for list in yrmn:
    outZSaT = ZonalStatisticsAsTable("I:/boundaries", "ID", "I:/rawfile%list%.tif", "I:/newfile%list%.dbf", "DATA", "SUM")

1 Answer 1

1

Python won't substitute variables like %list% into strings like how ModelBuilder does. Here's the most basic way to do it in Python using string concatenation:

import arcpy
from arcpy import env
from arcpy.sa import *
arcpy.CheckOutExtension("Spatial")

yrmn = ['200101', '200102', '200103', '200104']

for list in yrmn:
    in_value_raster = "I:/rawfile" + list + ".tif"
    out_table = "I:/newfile" + list + ".dbf"
    outZSaT = ZonalStatisticsAsTable("I:/boundaries", "ID", in_value_raster, out_table, "DATA", "SUM")

You could also use string formatting operations:

    in_value_raster = "I:/rawfile%s.tif" % list
    out_table = "I:/newfile%s.dbf" % list

Python purists would prefer the str.format() method, since the above string formatted may be deprecated in Python 3.x:

    in_value_raster = "I:/rawfile{}.tif".format(list)
    out_table = "I:/newfile{}.dbf".format(list)
2
  • I used the last one and it works. dmahr, you are a time saver. Thx a lot.
    – user25458
    Commented Jan 5, 2014 at 15:17
  • @user25458 Sure thing. Be sure to mark the question as answered if you're all set.
    – dmahr
    Commented Jan 5, 2014 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.