query regarding file handling.

ankita dutta ankita.dutta09 at gmail.com
Thu Nov 12 04:59:40 EST 2009


hi all,

i have a file of 3x3 matrix of decimal numbers(tab separated). like this :

0.02    0.38    0.01
0.04    0.32    0.00
0.03    0.40    0.02

now i want to read 1 row and get the sum of a particular row. but when i am
trying with the following code, i am getting errors :

*code*:
"
ln1=open("A.txt","r+")    # file "A.txt" contains my matrix
lines1=ln1.readlines()
n_1=[ ]

for p1 in range (0,len(lines1)):
    f1=lines1[p1]
    n_1.append((f1) )
print n_1
print  sum(n_1[0])

"

*output*:

['0.0200\t0.3877\t0.0011\n', '0.0040\t0.3292\t0.0001\n',
'0.0355\t0.4098\t0.0028\n', '0.0035\t0.3063\t0.0001\n',
'0.0080\t0.3397\t0.0002\n']

Traceback (most recent call last):
  File "A_1.py", line 20, in <module>
    print sum(nodes_1[0])
  File "/usr/lib/python2.5/site-packages/numpy/core/fromnumeric.py", line
993, in sum
    return _wrapit(a, 'sum', axis, dtype, out)
  File "/usr/lib/python2.5/site-packages/numpy/core/fromnumeric.py", line
37, in _wrapit
    result = getattr(asarray(obj),method)(*args, **kwds)
TypeError: cannot perform reduce with flexible type


* what I think:*

as the list is in form of   '0.0200\t0.3877\t0.0011\n'    ,  n_1[0]  takes
it as a whole string   which includes "\t" , i think thats why they are
giving error.

now how can i read only required numbers from this line
'0.0200\t0.3877\t0.0011\n'  and find their sum ?
can you kindly help me out how to properly code thing .



thank you,

regards
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091112/2338140b/attachment.html>


More information about the Python-list mailing list