如何使用msgpack进行读写?

发布于 2021-01-29 19:18:07

如何data使用msgpack对字典进行序列化/反序列化?

关注者
0
被浏览
43
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    Python文档似乎不是那么好,所以这里是我的尝试。

    安装

    pip install msgpack
    

    读写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)
    

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

    • 其他编程语言的支持
    • 阅读/写作表现
    • 紧凑度(文件大小)

    另请参阅:数据序列化格式的比较

    如果您想寻找一种制作配置文件的方法,则可能需要阅读我的短文《Python中的配置文件》。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看