【发布时间】:2017-04-12 20:59:40
【问题描述】:
根据 Python Cookbook,以下是如何将元组列表写入二进制文件:
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, '<idd', f)
而且效果很好。 对于读取(大量二进制数据),作者推荐如下:
>>> import numpy as np
>>> f = open('data.b', 'rb')
>>> records = np.fromfile(f, dtype='<i,<d,<d')
>>> records
array([(1, 2.3, 4.5), (6, 7.8, 9.0), (12, 13.4, 56.7)],
dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', '<f8')])
>>> records[0]
(1, 2.3, 4.5)
>>> records[1]
(6, 7.8, 9.0)
>>>
也不错,不过这个record不是普通的numpy数组。例如,type(record[0]) 将返回 <type 'numpy.void'>。更糟糕的是,我无法使用X = record[:, 0] 提取第一列。
有没有办法有效地将二进制文件中的列表(或任何其他类型)加载到普通的 numpy 数组中? 提前谢谢。
【问题讨论】:
标签: python arrays numpy binaryfiles