简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM