1

I have a binary file that contains a column of values. Using Python 3, I'm trying to unpack the data into an array or list.

file = open('data_ch04.dat', 'rb')

values = struct.unpack('f', file.read(4))[0]

print(values)

file.close()

The above code prints only one value to the console:

-1.1134038740480121e-29

How can I get all of the values from the binary file?

Here's a link to the binary file on Dropbox:

https://www.dropbox.com/s/l69rhlrr9u0p4cq/data_ch04.dat?dl=0

1 Answer 1

2

Your code only displays one float because it only reads four bytes.

Try this:

import struct

# Read all of the data
with open('data_ch04.dat', 'rb') as input_file:
    data = input_file.read()

# Convert to list of floats
format = '{:d}f'.format(len(data)//4)
data = struct.unpack(format, data)

# Display some of the data
print len(data), "entries"
print data[0], data[1], data[2], "..."
Sign up to request clarification or add additional context in comments.

3 Comments

I noticed the values are different if big-endian >f or little-endian <f is used to unpack the data. Is it possible to tell which approach is correct for this type of file?
Not generally, no. I would ask the person who produced the file what the byte-order is. Alternatively, you can run it both ways and see which one produces "reasonable" numbers.
I'll try to find out more details about the data, but your example seems to work. Thanks!

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.