Often we need to store objects. With pickle, we write collections such as lists to a data file. It supports many objects. The with-statement improves resource cleanup.
The important methods for using the pickle module include dump()
and load. We can place calls to these methods within "with" blocks for the cleanest and safest code.
The goal of this Python program is to write data to a binary pickle file, and then read it back it, demonstrating its equivalence.
string
literals in an initialization statement.pickle.dump()
. Dump()
writes the list contents in binary form to the file f.pickle
.pickle.dump()
, we ignore the original list in memory. We load that same data back from the disk with pickle.load()
.import pickle # Step 1: create input list data. list = ["one", "two", "three"] print("before:", list) # Step 2: open the file and call pickle.dump. with open("f.pickle", "wb") as f: pickle.dump(list, f) # Step 3: open the file and call pickle.load. with open("f.pickle", "rb") as f: data = pickle.load(f) print("after:", data)before: ['one', 'two', 'three'] after: ['one', 'two', 'three']
While other options for reading and writing files exist in Python (even newer formats like TOML), the pickle module remains a decent choice for simple data serialization.