query regarding file handling.

Himanshu himanshu.garg at gmail.com
Thu Nov 12 07:16:55 EST 2009


2009/11/12 ankita dutta <ankita.dutta09 at gmail.com>:
> 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 .
>

Yes you have it right. Split the string at spaces and convert the
numeric parts to floats before summing. Something along these lines :-

  1 ln1=open("A.txt","r+")    # file "A.txt" contains my matrix
  2 lines1=ln1.readlines()
  3 n_1=[ ]
  4
  5 for p1 in range (0,len(lines1)):
  6     f1=lines1[p1]
  7     n_1.append((f1) )
  8 print n_1
  9 import re
 10 nos = []
 11 for s in re.split('\s+', n_1[0]):
 12     if s != '':
 13         nos.append(float(s))
 14 print nos
 15 print  sum(nos)

Better still use the csv module as suggested.

Thank You,
++imanshu



More information about the Python-list mailing list