reading file contents to an array (newbie)

Jeff Epler jepler at unpythonic.net
Tue Jul 6 19:54:39 EDT 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 dale.py
[[  1.00000000e+00   2.00000000e+00   3.00000000e+00]
 [  4.00000000e+00   5.90000000e+00   6.00000000e+23]]
$ cat dale.py
import csv
from numarray import array, Float64

def sniff(f, delimeters=None):
    sample = "".join(f.readlines(3))
    f.seek(0, 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: <http://mail.python.org/pipermail/python-list/attachments/20040706/7c7116b4/attachment.sig>


More information about the Python-list mailing list