reading file contents to an array (newbie)

Jeff Epler jepler at
Wed Jul 7 01:54:39 CEST 2004

Here's my solution, using 2.3's "csv" module.  Unfortunately, it holds
the whole array in Python lists to pass to the array() constructor.

$ cat dale.ssv
1 2 3
4.0 5.9 6.0e23
$ python
[[  1.00000000e+00   2.00000000e+00   3.00000000e+00]
 [  4.00000000e+00   5.90000000e+00   6.00000000e+23]]
$ cat
import csv
from numarray import array, Float64

def sniff(f, delimeters=None):
    sample = "".join(f.readlines(3)), 0)
    return csv.Sniffer().sniff(sample, delimeters)

def file_to_array(f, dialect=None, kind=Float64, conv=float):
    if dialect is None:
        dialect = sniff(f)
    l = csv.reader(f, dialect)
    return array([map(conv, row) for row in l], kind)

print file_to_array(open("dale.ssv"))
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <>

More information about the Python-list mailing list