import pickle
# Example object to serialize
= {'name': 'Alice', 'age': 30, 'city': 'New York'}
data
# Serialize the object to a file
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
# Deserialize the object from the file
with open('data.pkl', 'rb') as f:
= pickle.load(f)
loaded_data
print(loaded_data)
Serialization
- Serialization is the process of converting a data structure or object into a format that can be easily stored or transmitted and later reconstructed (“de-serialized”).
The pickle
module
- In Python, the
pickle
module provides a very simple way to serialize and deserialize objects. - See the following example:
Other serialization formats: JSON and XML
JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are two other popular standard formats for serialization, similar to
pickle
but more widely used for interoperability and readability in various programming languages and applications. In other words: it is not restricted to Python.JSON is generally more lightweight and easier to work with in web applications, while XML provides more flexibility and is often used in more complex data exchange scenarios.
JSON
- A JSON file format would look like this, for example:
{
"name": "Alice",
"age": 30,
"city": "New York"
}
- JSON can be easily read with the language JavaScript, but also can be handled with Python using built-in module
json
(see documentation)
XML
- A XML file would look like this:
<person>
<name>Alice</name>
<age>30</age>
<city>New York</city>
</person>
- Python can handle XML files using the built-in module
xml.etree.ElementTree
, or with third-party libraries such asxmltodict
orlxml
.