Pickle is part of the Python library by default and is an important module whenever you need persistence between user sessions. As a module, pickle provides functionality to save Python objects between processes.
Whether you are programming for a database, game, forum, or other application where information must be saved between sessions, pickle helps save identifiers and settings. The pickle module can store data types such as Boolean values, strings and byte arrays, lists, dictionaries, functions, etc.
Note: The concept of pickle is also known as serialization, marshaling and flattening. However, the key is always the same - save the object to a file for later retrieval. pickle achieves this by writing the object to a long byte stream.
Pickle example code in Python
To write an object to a file, use the code in the following syntax:
import pickle object = Object() filehandler = open(filename, 'w') pickle.dump(object, filehandler)
The following is a real-life example:
import pickle import math object_pi = math.pi file_pi = open('filename_pi.obj', 'w') pickle.dump(object_pi, file_pi)
This fragment writes the contents of object_pi to the file handler file_pi, and the file handler file_pi is bound to the file filename_pi.obj in the execution directory.
To restore an object's value to memory, load the object from a file. Assuming pickle has not been imported for use, import it first:
import pickle filehandler = open(filename, 'r') object = pickle.load(filehandler)
The following code restores the value of pi:
import pickle file_pi2 = open('filename_pi.obj', 'r') object_pi2 = pickle.load(file_pi2)
The object is then ready for use again, this time as object_pi2. Of course, you can reuse the original name if you wish. This example uses different names for clarity.
Things About Pickle
Please keep the following in mind when using the pickle module:
The pickle protocol is specific to Python - it is not guaranteed to be cross-language compatible. You most likely won't be able to transfer the information to make it useful in Perl, PHP, Java, or other languages.
Compatibility is not guaranteed between different versions of Python. The incompatibility exists because not every Python data structure can be serialized by the module.
By default, the latest version of the pickle protocol is used. It remains that way unless you change it manually.
The above is the detailed content of How to save objects in Python using Pickle. For more information, please follow other related articles on the PHP Chinese website!