如何使用msgpack进行读写?

Mar*_*oma 6 python msgpack

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

Mar*_*oma 22

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

安装

pip install msgpack
Run Code Online (Sandbox Code Playgroud)

读写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', 'w') as outfile:
    msgpack.pack(data, outfile)

# Read msgpack file
with open('data.msgpack') as data_file:
    # data_loaded = json.load(data_file)
    data_loaded = msgpack.unpack(data_file)

print(data == data_loaded)
Run Code Online (Sandbox Code Playgroud)

备择方案

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

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

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

如果您正在寻找一种制作配置文件的方法,您可能希望阅读我的简短文章Python中的配置文件

  • msgpack 文件的推荐扩展名是什么? (3认同)
  • 我们现在只使用 pip install msgpack。根据 pypi,msgpack-python 已经过时了。 (2认同)