[Numpy-discussion] loadtxt issues

Sturla Molden sturla@molden...
Wed Mar 4 05:57:43 CST 2009

On 2/11/2009 6:40 AM, A B wrote:
> Hi,
> How do I write a loadtxt command to read in the following file and
> store each data point as the appropriate data type:
> 12|h|34.5|44.5
> 14552|bbb|34.5|42.5

> dt = {'names': ('gender','age','weight','bal'), 'formats': ('i4',
> 'S4','f4', 'f4')}

Does this work for you?

dt = {'names': ('gender','age','weight','bal'),
       'formats': ('i4','S4','f4', 'f4')}
with open('filename.txt', 'rt') as file:
    linelst = [line.strip('\n').split('|') for line in file]
n = len(linelst)
data = numpy.zeros(n, dtype=numpy.dtype(dt))
for i,(gender, age, weight, bal) in zip(range(n),linelst):
    data[i] = (int(gender), age, float(weight), float(bal))


More information about the Numpy-discussion mailing list