我有一个由科学设备创建的.bin文件,以及一个.h文件,描述数据结构(超过1000行)。
我想将这个文件读入python以进行进一步分析。我对 python 有一定的经验,但是完全被这个问题淹没了。我真的没有一个确切的问题,但我想知道,做到这一点的途径是什么,我需要学习什么?此时我什至不知道该谷歌什么。
如果我找不到更好的主意,我将不得不学习c,编写加载.bin文件的c代码,然后将数据存储在.csv文件中,然后我可以在python中读取该文件。
到目前为止我已经尝试过的(感谢 chatgpt):我使用 .h 文件使用 ctypesgen 创建了一个模块,并将其导入到我的 python 文件中。现在我不知道如何继续。这是数据的基本结构。一般来说应该包含3000包数据,每包数据包含测量数据以及其他数据。
PACK(struct xStatusType
{
struct priv_timeval TimeOfDayMaster;
struct IWG1Type IWG1Data;
uint8_t bPumpDataValid;
struct xPumpStatusType xPumpStatus;
uint8_t bDetDataValid;
struct xDetStatusType xDetStatus;
struct NTPStatType NTPStatus;
uint16_t InstrumentAction;
});
没有给出完整的结构定义,但这应该让您了解如何使用
ctypes
: 读写固定结构数据
import ctypes as ct
class A(ct.Structure):
_pack_ = 1 # to prevent padding bytes for misaligned data
_fields_ = (('a', ct.c_int32), # size 4
('b', ct.c_uint8), # size 1
('c', ct.c_uint16)) # size 2 (total 7)
def __repr__(self):
return f'A(a={self.a}, b={self.b}, c={self.c})'
class B(ct.Structure):
_pack_ = 1
_fields_ = (('a', A), # size 7
('b', ct.c_uint8)) # size 1 (total 8)
def __repr__(self):
return f'A(a={self.a}, b={self.b})'
with open('out.bin', 'wb') as fout:
# write a couple of records
a = A(1,2,3)
b = B(a, 4)
to_write = bytes(b)
print(to_write)
fout.write(to_write)
a = A(5,6,7)
b = B(a, 8)
to_write = bytes(b)
print(to_write)
fout.write(to_write)
print()
with open('out.bin', 'rb') as fin:
while data := fin.read(ct.sizeof(B)): # while breaks if no data read
print(data)
b = B.from_buffer_copy(data) # copy byte data into structure
print(b)
输出:
b'\x01\x00\x00\x00\x02\x03\x00\x04'
b'\x05\x00\x00\x00\x06\x07\x00\x08'
b'\x01\x00\x00\x00\x02\x03\x00\x04'
A(a=A(a=1, b=2, c=3), b=4)
b'\x05\x00\x00\x00\x06\x07\x00\x08'
A(a=A(a=5, b=6, c=7), b=8)