python二进制文件的读取与写入分别使用什么方法_从二进制文件读取/写入Python列表...

根据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提前。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值