[英]Reading a binary file header with Python
I have some binary data that I want to read via Python.我有一些我想通过 Python 读取的二进制数据。 I have the C code to do this, but I want to try it in Python.
我有 C 代码来执行此操作,但我想在 Python 中尝试它。
Let's say the header of the file is as follows:假设文件的 header 如下:
typedef struct
{
uint64_t message_time;
float lon, lat, alt;
int32_t extraint32[16];
float extrafloat[16];
char aircraft_name[100];
} AIRCRAFT_HEADER;
Using Python, I do the following:使用 Python,我执行以下操作:
from ctypes import *
class aircraft_header(Structure):
_fields_ = [('message_time', c_uint64),
('lon', c_float), ('lat', c_float), ('alt', c_float),
('extraint32[16]', c_int32),
('extrafloat[16]', c_float),
('aircraft_name[100]', c_char)
]
with open("../data/somefile.bin",mode='rb') as file:
result = []
allc = aircraft_header()
while file.readinto(allc) == sizeof(allc):
result.append((allc.message_time,
allc.lon, allc.lat, allc.alt,
allc.extraint32,
allc.extrafloat,
allc.aircraft_name))
This will throw the exception:这将引发异常:
AttributeError: 'aircraft_header' object has no attribute 'extraint32'
How do I resolve this?我该如何解决这个问题? Also, is there a more Pythonic way of reading this binary file?
另外,是否有更 Pythonic 的方式来读取这个二进制文件?
Take a look at the attributes available on an aicraft_header
object:查看
aicraft_header
object 上可用的属性:
>>> example = aircraft_header()
>>> [x for x in dir(example) if not x.startswith('_')]
['aircraft_name[100]', 'alt', 'extrafloat[16]', 'extraint32[16]', 'lat', 'lon', 'message_time']
You have an attribute that is named literally extraint32[16]
, which suggests you have an error in how your definining your Structure
.您有一个名为extraint32
extraint32[16]
的属性,这表明您在定义Structure
时存在错误。
Taking a look at ctypes documentation , I think you want:看看ctypes 文档,我想你想要:
from ctypes import *
class aircraft_header(Structure):
_fields_ = [('message_time', c_uint64),
('lon', c_float), ('lat', c_float), ('alt', c_float),
('extraint32', c_int32 * 16),
('extrafloat', c_float * 16),
('aircraft_name', c_char * 100)
]
This appears to behave as expected:这似乎表现得如预期:
>>> example.extraint32
<__main__.c_int_Array_16 object at 0x7fda7c9068c0>
>>> example.extraint32[0]
0
>>> example.extraint32[15]
0
>>> example.extraint32[16]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.