How do I read and write with msgpack? [closed]

2019-01-08 01:43发布

How do I serialize / deserialize a dictionary data with msgpack?

1条回答
地球回转人心会变
2楼-- · 2019-01-08 02:20

The Python docs seem not to be so good, so here is my try.

Installation

pip install msgpack

Read and Write 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)

Alternatives

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

See also: Comparison of data serialization formats

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

查看更多
登录 后发表回答