I am learning about object serialization for the first time. I tried reading and 'googling' for differences in the modules pickle and shelve but I am not sure I understand it. When to use which one? Pickle can turn every python object into stream of bytes which can be persisted into a file. Then why do we need the module shelve? Isn't pickle faster?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
pickle
is for serializing some object (or objects) as a single bytestream in a file.shelve
builds on top ofpickle
and implements a serialization dictionary where objects are pickled, but associated with a key (some string), so you can load your shelved data file and access your pickled objects via keys. This could be more convenient were you to be serializing many objects.Here is an example of usage between the two. (should work in latest versions of Python 2.7 and Python 3.x).
pickle
ExampleThis will dump the
integers
list to a binary file calledpickle-example.p
.Now try reading the pickled file back.
The above should output
[1, 2, 3, 4, 5]
.shelve
ExampleNotice how you add objects to the shelf via dictionary-like access.
Read the object back in with code like the following:
The output will be
'ints', [1, 2, 3, 4, 5]
.