使用Python解包二进制文件只返回一个值

时间:2015-11-19 21:40:27

标签: python python-3.x binary unpack

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

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

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

print(values)

file.close()

以上代码只向控制台输出一个值:

-1.1134038740480121e-29

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

这是Dropbox上二进制文件的链接:

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

1 个答案:

答案 0 :(得分:2)

您的代码只显示一个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], "..."