Python – substituting in a file


I use python 2.5, i like to replace certain variables in a txt file and write the complete data into new file.

i wrote a program to do the above,

from scipy import *

import numpy 

from numpy import asarray

from string import Template

def Dat(Par):

 Par = numpy.asarray(Par)

 Par[0] = a1

 Par[1] = a2

 Par[2] = a3

 Par[3] = a4

 sTemplate=Template(open('/home/av/W/python/data.txt', 'r').read()).safe_substitute(Par)

 open('/home/av/W/python/data_new.txt' ,'w').write(sTemplate)

Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)]


when i executed the above
*i obtained the error

'TypeError: 'function' object is unsubscriptable'

'data.txt' is a text file, i have placed $a1, $a2, $a3, $a4, i need to replace $a1 $a2 $a3 $a4 by 10.0 200.0 500.0 10.0

My constraints are i need to pass the values only by array like Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)]

please help me.

is this error due to python 2.5 version? or any mistakes in program

Best Solution

The error is here:

Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)]

which was probably meant to be

Init = numpy.asarray ([10.0, 200.0, 500.0, 10.0])

(note the swapped braces/parens). Since python found a "[" after "asarray" (which is a function), it throws an error, because you cannot subscribe (i.e. do something like x[17]) a function.