我如何使用 msgpack 读写?

How do I read and write with msgpack?

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

Python docs好像不太好,我试试看。

安装

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)

备选方案

  • CSV:超级简单的格式()
  • JSON:非常适合编写人类可读的数据;非常常用 (read & write)
  • YAML:YAML 是 JSON 的超集,但更易于阅读 (read & write, comparison of JSON and YAML)
  • pickle: 一种 Python 序列化格式 (read & write)
  • MessagePack (Python package): More compact representation ()
  • HDF5 (Python package): Nice for matrices ()
  • XML: 也存在*叹气* (read & write)

对于您的申请,以下内容可能很重要:

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

另请参阅:Comparison of data serialization formats

如果您更想寻找制作配置文件的方法,您可能需要阅读我的短文 Configuration files in Python