← Go Back

How to Save a Python Object to a File

To save a Python object (a list, a string, etc.) to a file, use the pickle standard module:

import pickle

# Save the list [1, 2, 3, 4] in the "obj.pickle" file.
obj = [1, 2, 3, 4]
with open("obj.pickle", "wb") as f:
pickle.dump(obj, f)

Then, to pick up that same object from the obj.pickle file:

with open("obj.pickle", "rb") as f:
obj = pickle.load(f)
print(obj) # [1, 2, 3, 4]

pickle is Python's standard object serialization protocol.

objects files pickle

🐍 You might also find interesting: