读入二进制文件Little Endian

2024-04-19 14:02:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个二进制文件,如下所示。 如何将此文件的内容读入变量

import struct 

with open("test-09.bin", "wb") as fp:
    fp.write(struct.pack("<4d", 3.14159, 42.0, 123.456, 987.654))

with open("test-09.bin", "rb") as fp:
    fp.read(struct.unpack("<4d", ????))

Tags: 文件testimport内容binaswith二进制
1条回答
网友
1楼 · 发布于 2024-04-19 14:02:29

逻辑是向后的-将文件内容作为参数读入unpack,这将返回未打包的数据-如下所示:

with open("test-09.bin", "rb") as fp:
    nums = struct.unpack("<4d", fp.read())

nums设置为:

(3.14159, 42.0, 123.456, 987.654)

更新:正如@tdelaney指出的,最好不要假设读取的大小,因此更全面的方法可能是:

format = "<4d"
size = struct.calcsize(format)
with open("test-09.bin", "rb") as fp:
    data = fp.read(size)
if len(data) == size:
    nums = struct.unpack("<4d", data)
else:
    print("short file read")

相关问题 更多 >