Skip to main content

How to Python's pickle module

··1 min·
Python Pickle
Makoto Morinaga
Author
Makoto Morinaga
A personal notebook for tech notes, coding, and system experiments.
Table of Contents

An overview of using Python’s pickle module for object serialization and deserialization, with file paths specified using pathlib.

Object Serialization
#

Serialize(save) objects to a file using pickle.

python
import pickle
from pathlib import Path

# Create an object to serialize
my_data = {'key': 'value', 'number': 42}

# Define the save path and serialize the object
path = Path('data.pkl')
with path.open('wb') as file:
    pickle.dump(my_data, file)

Object Deserialization
#

Deserialize (load) objects from a file using pickle.

python
# Define the path of the file to load
import pickle
from pathlib import Path

  path = Path('data.pkl')

  # Load the object from the file
  with path.open('rb') as file:
      data_loaded = pickle.load(file)
  print(data_loaded)

Cautionary Notes
#

Exercise caution when using pickle, especially during deserialization. Pickle can execute arbitrary code if the data is malicious. Always ensure that you unpickle data from trusted and verified sources to mitigate security risks.

Related

How to split a list into n parts in Python
··2 mins
List Python
Generating Image for Confusion Matrix and Classification Report in Python
··2 mins
Python Metric Classification Confusion-Matrix
How to handle jsonl in Python
··1 min
Python Jsonl