Omkar Omkar - 3 months ago 21
Python Question

From string library, template function doesnt work with int value?

I am trying to use Template from string. I have a directory with 100 csv files with data pertaining to each year.

For ex.:

yob1881.txt
yob1882.txt
yob1883.txt
yob1884.txt
yob1885.txt


Now i want to use template so that i can loop over all files. So i am using a range function like:

for year in range(1880,2011):
template = Template(/name/year$year)
template.substitute(year)


This is returning an error:

TypeError Traceback (most recent call last)
<ipython-input-4-85f21050945a> in <module>()
2 filepath = tp('/pythonDataProjects/Loan Granting/names/yob$year.txt')
3 year = '1880'
----> 4 print(filepath.substitute(year))

/Users/omkar/anaconda/lib/python3.5/string.py in substitute(*args, **kws)
127 raise ValueError('Unrecognized named group in pattern',
128 self.pattern)
--> 129 return self.pattern.sub(convert, self.template)
130
131 def safe_substitute(*args, **kws):

/Users/omkar/anaconda/lib/python3.5/string.py in convert(mo)
117 named = mo.group('named') or mo.group('braced')
118 if named is not None:
--> 119 val = mapping[named]
120 # We use this idiom instead of str() because the latter will
121 # fail if val is a Unicode containing non-ASCII characters.


TypeError: string indices must be integers

I know what the error is. However, i am not getting how to resolve it.

Any help?

Answer

Your issue is that you're not assigning the substitution when calling template.substitute(year). You need to format this like:

template.substitute(year=year)

Also, substitute() returns a new string, so you should either reassign this template or assign it to a new variable.

for year in range(1880,2011):
    template = Template("/name/year$year")
    template = template.substitute(year=year)

    # Or

    new_temp = template.substitute(year=year)

Suggestion

Is there a reason why you're not using the format() method? You can get the same results by doing

for year in range(1880,2011):
    template = "/name/yob{}.txt".format(year)