[英]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.
使用Python 3,我试图将数据解压缩到数组或列表中。
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: 这是Dropbox上二进制文件的链接:
https://www.dropbox.com/s/l69rhlrr9u0p4cq/data_ch04.dat?dl=0 https://www.dropbox.com/s/l69rhlrr9u0p4cq/data_ch04.dat?dl=0
Your code only displays one float
because it only reads four bytes. 您的代码仅显示一个
float
因为它仅读取四个字节。
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], "..."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.