Code for How to Use Pickle for Object Serialization in Python

You can also view the full code on github.

save_data_structures.py

import pickle

# define any Python data structure including lists, sets, tuples, dicts, etc.
l = list(range(10000))

# save it to a file
with open("list.pickle", "wb") as file:
    pickle.dump(l, file)

# load it again
with open("list.pickle", "rb") as file:
    unpickled_l = pickle.load(file)


print("unpickled_l == l: ", unpickled_l == l)
print("unpickled l is l: ", unpickled_l is l)

save_defined_objects.py

import pickle

class Person:
    def __init__(self, first_name, last_name, age, gender):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.gender = gender

    def __str__(self):
        return f"<Person name={self.first_name} {self.last_name}, age={self.age}, gender={self.gender}>"


p = Person("John", "Doe", 99, "Male")

# save the object
with open("person.pickle", "wb") as file:
    pickle.dump(p, file)

# load the object
with open("person.pickle", "rb") as file:
    p2 = pickle.load(file)

print(p)
print(p2)

save_dumps.py

import pickle

class Person:
    def __init__(self, first_name, last_name, age, gender):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.gender = gender

    def __str__(self):
        return f"<Person name={self.first_name} {self.last_name}, age={self.age}, gender={self.gender}>"

p = Person("John", "Doe", 99, "Male")

# get the dumped bytes
dumped_p = pickle.dumps(p)
print(dumped_p)

# write them to a file
with open("person.pickle", "wb") as file:
    file.write(dumped_p)

# load it
with open("person.pickle", "rb") as file:
    p2 = pickle.loads(file.read())

print(p)
print(p2)