Search⌘ K
AI Features

Saving Data to a Pickle File

Understand how to serialize Python data structures using the pickle module. Learn to create dictionaries with various data types, save them to files in binary format, and grasp the implications of using different pickle protocol versions for compatibility and data integrity.

We'll cover the following...

The pickle module works with data structures. Let’s build one.

Python 3.5
shell = 1
print (shell) #①
#1
entry = {} #②
entry['title'] = 'Dive into history, 2009 edition'
entry['article_link'] = 'http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition'
entry['comments_link'] = None
entry['internal_id'] = b'\xDE\xD5\xB4\xF8'
entry['tags'] = ('diveintopython', 'docbook', 'html')
entry['published'] = True
import time
entry['published_date'] = time.strptime('Fri Mar 27 22:20:42 2009') #③
print (entry['published_date'])
#time.struct_time(tm_year=2009, tm_mon=3, tm_mday=27, tm_hour=22, tm_min=20, tm_sec=42, tm_wday=4, tm_yday=86, tm_isdst=-1)

① Follow along in Python Shell #1.

② The idea here is to build a Python dictionary that could represent something useful, like an entry in an Atom feed. But I also want to ensure that it contains several different types of data, to show off the pickle module. Don’t read too much into these values.

③ The time module contains a data structure (struct_time) to represent a point in time (accurate to one millisecond) and functions to manipulate time ...