繁体   English   中英

使用Python解压缩二进制文件仅返回一个值

[英]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上二进制文件的链接:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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