1

I have a data file with 64-bit IEEE floating point data. I created it with the Python array module:

float_array = array('d', data_list)
float_array.tofile(out_fname)

where data_list is a simple Python list containing integers.

Now I want to open that file and read from it. I tried this:

fname = 'C:\Data_Files\Python64_Float'
file_object  = open(fname, "rb")

I tried reading it two ways:

data = struct.unpack('f', file_object.read(4))

AND

data = file_object.read()

but in both cases it returns an array of zeroes, which is not what the file contains. I can open and read this file with another tool, but I need to read it in Python.

I also tried reading this with array.fromfile, but Visual Studio says "module 'array' has no attribute 'fromfile' -- but according to the Python site on the array module, it does have a fromfile attribute.

So my question is: how can I read a file created by the Python array module as 64-bit float?

Thanks for any help.

1 Answer 1

1

You need to write your list as bytes into a file, then use array.frombytes method to read it.

Here is a full example:

Writing

import array

data_list = [1, 2, 3, 4]
float_array = array.array('d', data_list)
# write float_array as bytes
with open("Python64_Float", "wb") as fout:
    float_array.tofile(fout)

Reading

Now, use array.frombytes to read it just like so:

import array

another_float_array = array.array('d', [])
with open("Python64_Float", "rb") as fin:
    another_float_array.frombytes(fin.read())
print(another_float_array)
#array('d', [1.0, 2.0, 3.0, 4.0])
Sign up to request clarification or add additional context in comments.

1 Comment

Glad I could help !

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.