msgpack将字符串数据恢复为二进制

时间:2019-01-12 16:25:35

标签: python msgpack

How do I read and write with msgpack?中,给出了一个答案(https://stackoverflow.com/a/43442195)如何将数据转储到磁盘并读回。

我不得不调整那里给出的答案(即:添加用于读写的“ b”选项)以使其工作。但是从磁盘读取的数据仍然不同,因为从磁盘读取的字符串现在似乎是二进制的。

如何避免这种情况?

这是我改编的代码:

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:
    msgpack.pack(data, outfile)

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

print(data == data_loaded)
print("data:", data)
print("data_loaded:", data_loaded)

输出:

False
data: {'a list': [1, 42, 3.141, 1337, 'help'], 'a string': 'bla', 'another dict': {'foo': 'bar', 'key': 'value', 'the answer': 42}}
data_loaded: {b'a list': [1, 42, 3.141, 1337, b'help'], b'a string': b'bla', b'another dict': {b'foo': b'bar', b'key': b'value', b'the answer': 42}}

该版本(msgpack._version.py)似乎是:

version = (0, 6, 0)

1 个答案:

答案 0 :(得分:0)

阅读时

设置raw=False可以达到目的。代码:

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:
    msgpack.pack(data, outfile, )

# Read msgpack file
with open('data.msgpack', "rb") as data_file:
    # data_loaded = json.load(data_file)
    data_loaded = msgpack.unpack(data_file,raw=False)

print(data == data_loaded)
print("data:", data)
print("data_loaded:", data_loaded)

输出:

True
data: {'a list': [1, 42, 3.141, 1337, 'help'], 'a string': 'bla', 'another dict': {'foo': 'bar', 'key': 'value', 'the answer': 42}}
data_loaded: {'a list': [1, 42, 3.141, 1337, 'help'], 'a string': 'bla', 'another dict': {'foo': 'bar', 'key': 'value', 'the answer': 42}}