根据Python食谱,以下是如何写入二进制文件的元组列表:
from struct import Struct
def write_records(records, format, f):
'''
Write a sequence of tuples to a binary file of structures.
'''
record_struct = Struct(format)
for r in records:
f.write(record_struct.pack(*r))
# Example
if __name__ == '__main__':
records = [ (1, 2.3, 4.5),
(6, 7.8, 9.0),
(12, 13.4, 56.7) ]
with open('data.b', 'wb') as f:
write_records(records, '
为了阅读(大量的二进制数据),作者建议如下:
>>> import numpy as np
>>> f = open('data.b', 'rb')
>>> records = np.fromfile(f, dtype='
>>> records
array([(1, 2.3, 4.5), (6, 7.8, 9.0), (12, 13.4, 56.7)],
dtype=[('f0', '
>>> records[0]
(1, 2.3, 4.5)
>>> records[1]
(6, 7.8, 9.0)
>>>这也不错,但是这个record不是一个普通的numpy数组。例如,type(record[0])将返回。更糟糕的是,我无法使用X = record[:, 0]提取第一列。
有没有办法有效地加载列表(或任何其他类型)从二进制文件到正常的numpy数组?
Thx提前。