python的pickle的基本用法

时间:2017-07-29 19:43:31

标签: python-3.x pickle

我正在尝试学习如何使用Python中的序列化功能pickle。我已经写了这3个基本程序:

第一个程序:

import pickle

# An arbitrary collection of objects supported by pickle.
data = {
    'a': [1, 2.0, 3, 4+6j],
    'b': ("character string", b"byte string"),
    'c': set([None, True, False])
}

with open('data2.txt', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

第二节目:

import pickle

data = None

with open('data2.txt', 'rb') as f:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    data = pickle.load(f)


data['name'] = 'John'

with open('data2.txt', 'ab') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

第3节目:

import pickle

data = None

with open('data2.txt', 'rb') as f:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    data = pickle.load(f)


print(data)

整个测试的想法是看看泡菜是如何工作的。我创建一个字典,添加一些值和"腌制"他们到一个文件。然后在另一个模块中,我" unicked"数据并添加另一个键,值为dict和" pickle"它再次到同一个文件。最后,在第三个模块中,我" unsicked" dict并打印它,我无法看到第二个模块中添加的数据。有谁知道为什么?提前致谢。

1 个答案:

答案 0 :(得分:0)

您正在覆盖文件,但是当您将字典读入data变量时,您将读取整个dict对象,然后使用新变量重写整个dict。这等效于附加。

您需要在第二个程序中将ab更改为wb

with open('data2.txt', 'ab') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

您可以在此处https://docs.python.org/3/library/pickle.html#pickle.dump

阅读文档

它明确指定了应以写二进制模式打开文件。