Reputation: 309929
I'm trying to use numpy.fromfile
to read a structured array (file header) by passing in a user defined data-type. For some reason, my structured array elements are coming back as 2-d Arrays instead of flat 1D arrays:
headerfmt='20i,20f,a80'
dt = np.dtype(headerfmt)
header = np.fromfile(fobj,dtype=dt,count=1)
ints,floats,chars = header['f0'][0], header['f1'][0], header['f2'][0]
# ^? ^? ^?
How do I modify headerfmt
so that it will read them as flat 1D arrays?
Upvotes: 4
Views: 2006
Reputation: 284602
If the count
will always be 1, just do:
header = np.fromfile(fobj, dtype=dt, count=1)[0]
You'll still be able to index by field name, though the repr
of the array won't show the field names.
For example:
import numpy as np
headerfmt='20i,20f,a80'
dt = np.dtype(headerfmt)
# Note the 0-index!
x = np.zeros(1, dtype=dt)[0]
print x['f0'], x['f1'], x['f2']
ints, floats, chars = x
It may or may not be ideal for your purposes, but it's simple, at any rate.
Upvotes: 2