Pickle in python

Pickle in python

In Python, the pickle module provides a way to serialize and deserialize Python objects. Serialization is the process of converting an object into a stream of bytes, while deserialization is the reverse process of reconstructing the object from the stream of bytes.

Here’s an example of how to use pickle to serialize an object and save it to a file:

pythonCopy codeimport pickle

# Define an object to serialize
my_data = {'name': 'John', 'age': 30, 'city': 'New York'}

# Open a file in binary mode and serialize the object to the file
with open('my_data.pkl', 'wb') as file:
    pickle.dump(my_data, file)

In the above example, the dump() method is used to serialize the my_data object and save it to the file my_data.pkl. The 'wb' mode is used to open the file in binary mode for writing.

To deserialize the object from the file, you can use the load() method:

pythonCopy codeimport pickle

# Open the file in binary mode and deserialize the object from the file
with open('my_data.pkl', 'rb') as file:
    my_data = pickle.load(file)

# Print the deserialized object
print(my_data)

In the above example, the load() method is used to deserialize the object from the file my_data.pkl. The 'rb' mode is used to open the file in binary mode for reading. Finally, the deserialized object is printed to the console.

Note that pickle is not secure and should only be used to serialize and deserialize trusted data. Untrusted data could potentially contain malicious code that could execute when the data is deserialized.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Share this post
[social_warfare]
Files input and output
Exceptions in python

Get industry recognized certification – Contact us

keyboard_arrow_up