Omkar Omkar - 4 months ago 30
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.:


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)

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/ in substitute(*args, **kws)
127 raise ValueError('Unrecognized named group in pattern',
128 self.pattern)
--> 129 return self.pattern.sub(convert, self.template)
131 def safe_substitute(*args, **kws):

/Users/omkar/anaconda/lib/python3.5/ in convert(mo)
117 named ='named') or'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?


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


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)


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)