Pickle can be used to serialize and deserialize objects. A seralized object can be saved and loaded from the disk. Pickling is a method to convert an object (list, dict, etc) to a file and vice versa.
The idea is to save one or more objects in one script and load them in another. You can also use it to save program or game states.
We will save and load using a binary file, as this saves disk space.
Related course: Complete Python Bootcamp: Go from zero to hero in Python
To use pickling, import the pickle module.
Create an object and seralize it. Then write it to a file using a file object.
Now that the object is saved to a file, you can load it (unpickle it). In the example below we load the object from the file.
Load the pickle module, open then the file for reading then load the data with pickle.load(). You can load it into any variable you want, but I’ve used the same name for convenience (exampleObj).
This will show you the previously saved object:
Try the exercises below:
- Save and load an object from a file
- Try loading more than one object from a file