pickle.dump/load 和 pickle.dumps/loads 有什么区别?

What are the differences between pickle.dump/load and pickle.dumps/loads?

我开始学习用于对象序列化和反序列化的 pickle 模块。

我知道pickle.dump是用来将代码存储为字节流(序列化),而pickle.load本质上是相反的,将字节流转回一个python 对象。 (反序列化)。

但是pickle.dumpspickle.loads是什么,它们与pickle.dumppickle.load有什么区别呢?我查看了文档,但我无法区分两者。

From the documentation:

pickle.dumps(obj, protocol=None, *, fix_imports=True, buffer_callback=None) ; Return the pickled representation of the object obj as a bytes object, instead of writing it to a file.

pickle.loads(data, /, *, fix_imports=True, encoding="ASCII", errors="strict", buffers=None) Return the reconstituted object hierarchy of the pickled representation data of an object. data must be a bytes-like object.

dumpdumps的区别在于dump将pickled对象写入一个打开的文件,而dumpsreturns将pickled对象写为bytes。文件必须以二进制模式打开才能写入。对象的 pickled 版本与 dumpdumps.

完全相同

因此,如果您对对象 obj 执行以下操作:

with open("pickle1", "wb") as f:
    pickle.dump(obj, f)
with open("pickle2", "wb") as f:
    f.write(pickle.dumps(obj))

你最终会得到两个内容完全相同的文件。

这同样适用于加载 - load 从打开的(可读)文件对象“unpickles”,loads 使用 bytes 对象。