On Thu, 12 Nov 2009 09:59:40 -0000, ankita dutta <ankita.dutt...@gmail.com> wrote:

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

You can iterate through the file line by line, so there's no need to read the whole thing in one go like this.

n_1=[ ]

for p1 in range (0,len(lines1)):
    f1=lines1[p1]

If you ever write range(len(some_list)) in a 'for' statement, you're almost certainly making life harder for yourself than you need to. Since all you use 'pl' for is pulling out the 'current' line, you might as well just iterate through the list, i.e. replace those two lines with this:

for fl in lines1:

Better, as I mentioned earlier you can skip the whole business of slurping the file in using 'readlines' and read it one line at a time:

for fl in ln1:

    n_1.append((f1) )
print n_1
print  sum(n_1[0])

[snip]

* 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.

You think right.

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 .

Read the line (as before), then split it on whitespace (the tabs in this case), and then sum the resulting list. Or as Chris said, get the 'csv' module to do the hard work for you.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to