Member-only story

Pickle Quickstart — Saving & Loading Python Objects for Beginners

Liu Zuo Lin
2 min readAug 26, 2021

--

Did you know that you can save Python objects like lists, dictionaries and whatnot (most things in Python) in a file? We can do this easily with the pickle package, and we only need to know 3 lines of code!

Importing pickle

import pickle

To use pickle, we first need to import pickle.

Saving an object

Let’s say we have a list called fruits containing some fruits, and we want to save this list for future use for whatever reason. We can save it using the following line:

fruits = ["apple", "orange", "pear"]
pickle.dump(fruits, open("out.sav", "wb"))

This pickle.dump function essentially saves your fruits list in a file called out.sav (change this as you please), which we can reuse again and again. The “wb” option refers to “write binary”, and remember to include this option!

Loading an object

Let’s say we have an existing .sav file containing an object that we want to use. We now need to open this .sav file and load this object, and we can do this using the following line:

fruits = pickle.load(open("out.sav", "rb"))

--

--

Liu Zuo Lin
Liu Zuo Lin

Written by Liu Zuo Lin

SWE @ Meta | [Ebook] 101 Things I Never Knew About Python: https://payhip.com/b/vywcf

No responses yet