解压一个只有 Python returns 一个值的二进制文件

Unpacking a binary file with Python only returns one value

我有一个包含一列值的二进制文件。使用 Python 3,我试图将数据解压缩到数组或列表中。

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

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

print(values)

file.close()

以上代码只向控制台打印一个值:

-1.1134038740480121e-29

如何从二进制文件中获取所有值?

这是 Dropbox 上二进制文件的 link:

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

您的代码只显示一个 float 因为它只读取四个字节。

试试这个:

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