我该如何使用msgpack将字典data
进行序列化/反序列化操作?
Python文档似乎不太好,所以这里是我的尝试。
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)
另请参见:数据序列化格式比较
如果您更想找一种制作配置文件的方法,您可能想阅读我的短文 Python中的配置文件。
rb
标志(我已经阅读过,但不确定是否适用于写入)。 - GruberTypeError: write() argument must be str, not bytes
。我正在使用 Py3.7。 - Volatil3