Search code examples
pythonpython-3.xbinaryunpack

Unpacking a binary file with Python only returns one value


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


Solution

  • 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], "..."