how to read in an array in text file?
Bengt Richter
bokr at oz.net
Sun Nov 9 12:25:17 EST 2003
On Sun, 9 Nov 2003 12:17:39 +0100, "Ulrich Petri" <ulope at gmx.de> wrote:
>"Yun Mao" <maoy at cis.upenn.edu> schrieb im Newsbeitrag
>news:bokiea$bn00$1 at netnews.upenn.edu...
>> 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...
>>> from StringIO import StringIO
>>> f = 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 row in data:
... 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
More information about the Python-list
mailing list