pickle Example
This page was last reviewed on Apr 3, 2024.
Dot Net Perls
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 3, 2024 (edit link).
© 2007-2024 Sam Allen.