如何使用msgpack进行读写?

2024-03-29 10:35:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: data字典序列化msgpack
1条回答
网友
1楼 · 发布于 2024-03-29 10:35:06

这个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', '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)

替代品

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

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

另请参见:Comparison of data serialization formats

如果您正在寻找创建配置文件的方法,那么您可能需要阅读我的短文Configuration files in Python

相关问题 更多 >