每天CookBook之Python-104

  • 读写二进制数组数据
from struct import Struct


def write_records(records, format, f):
    record_struct = Struct(format)
    for r in records:
        f.write(record_struct.pack(*r))


def unpack_records(format, data):
    record_struct = Struct(format)
    return (record_struct.unpack_from(data, offset) for offset in range(0, len(data), record_struct.size))


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)

    from collections import namedtuple

    Record = namedtuple('Record', ['kind', 'x', 'y'])

    with open('data.b', 'rb') as f:
        data = f.read()

        for rec in unpack_records('<idd', data):
             record = Record(*rec)
             print(record)
Record(kind=1, x=2.3, y=4.5)
Record(kind=6, x=7.8, y=9.0)
Record(kind=12, x=13.4, y=56.7)
posted @ 2016-07-29 22:03  4Thing  阅读(108)  评论(0编辑  收藏  举报