How to Python's pickle module

How to Python's pickle module

January 18, 2024(January 18, 2024)
python, pickle

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.

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.

# 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.