tags:

views:

94

answers:

4

Hi,

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)]

Dat(Init)

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

+3  A: 

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.

balpha
Thanks, i tried,but now i am facing new errorPar[0] = a1NameError:global name 'a1' is not defined
Well, have you defined a1 anywhere?
balpha
You probably meant this: Par[0] = "a1" (or with the dollar sign?)
balpha
I swapped the parenthesis and if i execute,NameError: global name 'a1' is not defined i mean 'a1' with out dollar sign
In my program a1 is defined only in 6th line from top and in my text file i have only one as $a1
A: 
Init = numpy.asarray [(10.0, 200.0, 500.0, 10.0)]

This is your problem. numpy.asarray is a function, and you are trying to use it as a list (hence the exception). Flip the brackets and parentheses and try that.

Vince
Thanks but after changing the brackets, it shows different error
A: 

The line

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

should almost certainly be

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

I believe that is what is causing your "'function' object is unsubscriptable" error

Ian Clelland
A: 

from scipy import *

import numpy

from numpy import asarray

from string import Template

def Dat(Par):

Par = numpy.asarray(Par)

ParDict =dict(a1 = Par[0], a2 = Par[1],a3 = Par[2],a4 = Par[3])

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

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

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

Dat(Init)

In this way its works fine.