how to read in an array in text file?

Y

Yun Mao

Hi, what's the easy way of reading in a two-dimentional array from a text
file?
The text file looks like this:
0.1 1.1 2.3 12.1
0.3 33.0 4.1 1.1

I'm using Numeric Python now. Other solutions are also welcome. Thanks a
lot!
Yun
 
U

Ulrich Petri

Yun Mao said:
Hi, what's the easy way of reading in a two-dimentional array from a text
file?
The text file looks like this:
0.1 1.1 2.3 12.1
0.3 33.0 4.1 1.1

I'm using Numeric Python now. Other solutions are also welcome. Thanks a
lot!
Yun

f = file("myfile", "r")
data = [line.split() for line in f]
f.close()

HTH

Ciao Ulrich
 
B

Bengt Richter

Yun Mao said:
Hi, what's the easy way of reading in a two-dimentional array from a text
file?
The text file looks like this:
0.1 1.1 2.3 12.1
0.3 33.0 4.1 1.1

I'm using Numeric Python now. Other solutions are also welcome. Thanks a
lot!
Yun

f = file("myfile", "r")
data = [line.split() for line in f]
# or (untested), to get floats when you access data[row][col]
data = [map(float,line.split()) for line in f]
f.close()

Hate to leave that "(untested)" ... so, simulating the file with StringIO...
... 0.1 1.1 2.3 12.1
... 0.3 33.0 4.1 1.1
... """)
>>> data = [map(float,line.split()) for line in f]
>>> data
[[0.10000000000000001, 1.1000000000000001, 2.2999999999999998, 12.1], [0.29999999999999999, 33.0
, 4.0999999999999996, 1.1000000000000001]]
... for colitem in row: print '%10.3f' %colitem,
... print
...
0.100 1.100 2.300 12.100
0.300 33.000 4.100 1.100

Regards,
Bengt Richter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top