Home > Backend Development > Python Tutorial > How Does Python\'s Pickle Module Serialize and Deserialize Objects?

How Does Python\'s Pickle Module Serialize and Deserialize Objects?

Patricia Arquette
Release: 2024-11-29 01:05:12
Original
935 people have browsed it

How Does Python's Pickle Module Serialize and Deserialize Objects?

Understanding Pickle for Object Serialization: Preserving Python Objects

Pickle in Python provides a convenient mechanism to serialize Python objects into a binary format for storage or transmission. With pickle, you can seamlessly save complex data structures, including dictionaries, into files or bytes-like objects.

Serialization of a Dictionary

To write a new file and dump a dictionary into it using pickle, follow these steps:

import pickle

a = {'hello': 'world'}

with open('filename.pickle', 'wb') as handle:
    pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)
Copy after login

The pickle.dump() method serializes the dictionary 'a' into the binary file 'filename.pickle'. The protocol argument specifies the level of serialization compatibility.

Deserialization

To retrieve the serialized dictionary from the file:

with open('filename.pickle', 'rb') as handle:
    b = pickle.load(handle)
Copy after login

The pickle.load() method reads the binary data and reconstructs the original dictionary 'b'.

Versatility Beyond Dictionaries

Pickle is not limited to serializing dictionaries. It can handle various Python objects, including instances of custom classes and complex data structures. For example:

import datetime
today = datetime.datetime.now()
a = [{'hello': 'world'}, 1, 2.3333, 4, True, "x",
     ("y", [[["z"], "y"], "x"]), {'today', today}]
Copy after login

Limitations

While pickle is versatile, some objects cannot be pickled. This includes objects that rely on system resources, such as open file handles.

The above is the detailed content of How Does Python\'s Pickle Module Serialize and Deserialize Objects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template