I have a question about reading array from file.

I wrote some array at file like below.

file name: xy0.dat
[2, 4, 6]
[4, 8, 12]
...
...

Now, I want to read this array(not string) at my original file.

I want to define x0[0] = [2,4,6] and
x0[1] = [4,8,12]
...
-------------------------code---------------------------------------------------
from numpy import*
from scipy import*
import array

x0 = zeros(10000)

inFile = open('xy0.dat', 'r')
x0=[]
for line in inFile.readlines():
line.split()
x0.append(line)

print x0[0]

---------------------------result-----------------------------------------------------------------
[2, 4, 6]
----------------------------Question------------------------------------------------------------------------
okay. but it looks like string, not array.

because if I change the last part like below, there is some error message.

------------------------------Question code----------------------------------------------------------------

from numpy import*
from scipy import*
import array

x0 = zeros(10000)


inFile = open('xy0.dat', 'r')
x0=[]
for line in inFile.readlines():
line.split()
x0.append(line)

a = x0[0]
print sum(a)
---------------------Question result------------------------------------

Traceback (most recent call last):
File "ex4.py", line 15, in <module>
print sum(a)
File "/usr/lib/python2.5/site-packages/numpy/core/fromnumeric.py", line 633, in sum
return _wrapit(x, '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


please help me....

Editor's note:
Please use the [code=python] and [/code] tag pair to enclose your python code.

If your data file is created from a list of lists, then you you need to save(dump) and load it as a complete object using Python module pickle.

If your data file is just a text file of lines that look like lists, then you have to do some processing ...

"""
file xy0.dat contains
[2, 4, 6]
[4, 8, 12]
...
"""

#from numpy import*
#from scipy import*
#import array

#x0 = zeros(10000)

x0 = []
for line in file('xy0.dat'):
    #print line, type(line)  # test
    line = line.lstrip('[')
    line = line.rstrip(']\n')
    #print line, line.split(',')  # test
    line_list = [int(x) for x in line.split(',')]
    x0.append(line_list)

a = x0[0]
print a, type(a)  # test
print sum(a)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.