【问题标题】:How do I read and write with msgpack?我如何使用 msgpack 读写?
【发布时间】:2023-03-04 22:58:01
【问题描述】:

如何用msgpack 序列化/反序列化字典data

【问题讨论】:

    标签: python msgpack


    【解决方案1】:

    Python docs 似乎不太好,所以这是我的尝试。

    安装

    pip install msgpack
    

    读写消息包

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import msgpack
    
    # Define data
    data = {
        "a list": [1, 42, 3.141, 1337, "help"],
        "a string": "bla",
        "another dict": {"foo": "bar", "key": "value", "the answer": 42},
    }
    
    # Write msgpack file
    with open("data.msgpack", "wb") as outfile:
        packed = msgpack.packb(data)
        outfile.write(packed)
    
    # Read msgpack file
    with open("data.msgpack", "rb") as data_file:
        byte_data = data_file.read()
    
    data_loaded = msgpack.unpackb(byte_data)
    print(data == data_loaded)
    

    替代方案

    对于您的应用程序,以下内容可能很重要:

    • 其他编程语言的支持
    • 读/写性能
    • 紧凑性(文件大小)

    另见:Comparison of data serialization formats

    如果您正在寻找一种制作配置文件的方法,您可能想阅读我的短文Configuration files in Python

    【讨论】:

    • 我们现在只使用 pip install msgpack。根据 pypi,msgpack-python 已过时。
    • msgpack 文件的推荐扩展名是什么?
    • 好吧,我会推荐msgpack。但我也不知道任何其他支持 msgpack 的 Python 包。
    • msgpack._packer.Packer._pack TypeError: can't serialize 1.0
    • 对我来说,当使用更新版本的 python 时,必须将 rb 标志添加到文件打开函数中(我已阅读,不确定是否编写)。
    最近更新 更多