0

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)

enter image description here

1
  • 1
    fid is the open fike that has a read method. binvalues is an array.array which can hold values, but certainly can't read anything. Commented Dec 1, 2022 at 16:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

fid is his open file, which has a read

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.