Generating file names using Python string formatting

08-29-2014 09:53 AM

Generating file names using Python string formatting

This is a little tutorial on using Python string formatting to set up output file names.

You can use python string formatting to have full control over leading zeros in iteration. Also file naming can determine file format: to save a tif instead of an esri grid, specify a folder workspace output that ends with ".tif."

You can use the modern ".format()" string formatting instead of the old (but still supported C-like "%" formatting I used above. Which is best? I think the % syntax was going to be deprecated but many programmers just like it so it unlikely to go away - it's still there in Python 3.4. However, I am liking the new form the more I use it, it's a little more powerful and I think it's easier to read (and therefore debug).

>>> "%03d" % 3


>>> "{0:03d}".format(3)


Here's an example in code.

outrastName = 'Rel_elv{03d}.tif".format(k) # Python 2.6+

outrastName = 'Rel_elv%03d.tif" % k # deprecated - but still works

In ModelBuilder you can use this technique to great effect using the Calculate Value tool, with a string output. The built-in variable %n is the dynamically set iteration variable. The parameters for Calculate Value would be:



Code block:

(not needed)

Data Type:

String (or the default Variant will work too)

Make the output data element (Value) a precondition to your final processing step to make sure the filename gets created first.

Then you can use the string in the output of your final processing step in the iterating model:


(or, to use the current (runtime) workspace instead of the one auto-populated by model builder at edit time:


Version history
Revision #:
1 of 1
Last update:
‎08-29-2014 09:53 AM
Updated by: