Reputation: 149
I am getting the "object has no attribute" error. AttributeError: The "array.array" object has no attribute "read." Attached code as below. Kindly guide me on how to resolve the error.
import os
from functools import reduce
import numpy
import array
from utils import *
def load_raw_data_with_mhd(filename):
meta_dict = read_meta_header(filename)
dim = int(meta_dict['NDims'])
assert(meta_dict['ElementType']=='MET_FLOAT')
arr = [int(i) for i in meta_dict['DimSize'].split()]
volume = reduce(lambda x,y: x*y, arr[0:dim-1], 1)
pwd = os.path.split(filename)[0]
if pwd:
data_file = pwd +'/' + meta_dict['ElementDataFile']
else:
data_file = meta_dict['ElementDataFile']
print (data_file)
fid = open(data_file,'rb')
binvalues = array.array('f')
binvalues.read(fid, volume*arr[dim-1])
if is_little_endian(): # assume data in file is always big endian
binvalues.byteswap()
fid.close()
data = numpy.array(binvalues, numpy.float)
data = numpy.reshape(data, (arr[dim-1], volume))
return (data, meta_dict)
Upvotes: 0
Views: 3222
Reputation: 21
It looks like the error is being caused by the line
binvalues.read(fid, volume*arr[dim-1])
. In this line, you are trying to call the read method on an array.array object, but this class does not have a read method.
To fix this error, you can use the fromfile method of the array module to read the data from the file, like this:
binvalues = array.array('f')
binvalues.fromfile(fid, volume*arr[dim-1])
This should read the binary data from the file into the array.array object.
You may also want to consider using the struct module to read the binary data from the file, as this may be more efficient than using the array module. The struct module allows you to specify the format of the binary data you want to read, and then directly read the data into a numpy array without having to first create an array.array object.
For example, you could use the following code to read the binary data from the file using the struct module:
fmt = '>' + 'f'*(volume*arr[dim-1])
# the format string specifies that the data is in big-endian format and consists of a sequence of float values
data = numpy.fromfile(fid, dtype=numpy.float, count=volume*arr[dim-1], sep='')
# read the data from the file
You can then use the data array in the rest of your code.
Upvotes: 2