簡體   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