Pickle. 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.
Example. The goal of this Python program is to write data to a binary pickle file, and then read it back it, demonstrating its equivalence.
Step 1 In this example, we create a list with 3 string literals in an initialization statement.
Step 2 We pass the list to pickle.dump(). Dump() writes the list contents in binary form to the file f.pickle.
Step 3 After we call 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']
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 3, 2024 (edit link).