In this tutorial, we will learn how to use the pickle module in Python. Pickle is a built-in Python module that enables us to easily serialize and deserialize objects in an efficient and straightforward manner.
It’s particularly useful for storing objects in a persistent manner, such as saving them to a file. So, let’s dive into the steps on how to use pickle in Python.
Step 1: Import the Pickle Module
To start working with the pickle module, we first need to import it into our Python script. Simply add the following line at the beginning of your script:
1 |
import pickle |
Step 2: Create an Object to Serialize
In this example, we’ll create a sample dictionary object to demonstrate the process of serialization using pickle.
1 2 3 4 5 |
sample_dict = { 'name': 'John', 'age': 28, 'location': 'New York' } |
Step 3: Serialize the Object and Write to a File
To serialize the object and write it to a file, we need to open a file in binary write mode (wb
) and then use the function pickle.dump()
to write the serialized object to the file.
1 2 3 4 |
# Open a file in binary write mode with open('sample_file.pkl', 'wb') as file: # Serialize the object and write it to the file pickle.dump(sample_dict, file) |
The extension .pkl
is a common convention to indicate that the file contains a pickled object, but it’s not strictly required – you can use any extension you prefer.
Step 4: Read the Serialized Object From the File
Now, we’ll demonstrate how to deserialize an object from a file using pickle. First, we need to open the file in binary read mode (rb
). Then, we’ll use the function pickle.load()
to read the serialized object and deserialize it back into a Python object.
1 2 3 4 |
# Open the file in binary read mode with open('sample_file.pkl', 'rb') as file: # Deserialize the object from the file loaded_dict = pickle.load(file) |
Step 5: Verify the Deserialized Object
Finally, let’s print the deserialized object to verify that it matches our original object.
1 |
print(loaded_dict) |
The output should be:
{'name': 'John', 'age': 28, 'location': 'New York'}
Full Code
Here’s the complete code for the example above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import pickle sample_dict = { 'name': 'John', 'age': 28, 'location': 'New York' } with open('sample_file.pkl', 'wb') as file: pickle.dump(sample_dict, file) with open('sample_file.pkl', 'rb') as file: loaded_dict = pickle.load(file) print(loaded_dict) |
Conclusion
In this tutorial, we learned about the pickle module in Python and how to use it to easily serialize and deserialize Python objects. This can be particularly helpful for storing objects in a persistent manner, such as saving them to a file. Now that you know the basics of using pickle, you can start implementing it in your Python projects for efficient and straightforward object serialization and deserialization.