Skip to content

Instantly share code, notes, and snippets.

@lawsofthought
Created June 26, 2017 17:03
Show Gist options
  • Save lawsofthought/914706f2b38f985985afa8448c708f49 to your computer and use it in GitHub Desktop.
Save lawsofthought/914706f2b38f985985afa8448c708f49 to your computer and use it in GitHub Desktop.
A Python script to read/write pickle files
import cPickle as pickle
ongoing_list_dict = dict(subject_1 = 7,
subject_7 = 42,
subject_101 = 3)
# Write the dictionary to file
with open('ongoing_list.pkl', 'wb') as f:
pickle.dump(ongoing_list_dict, f, protocol=2)
# Read it back in
with open('ongoing_list.pkl', 'rb') as f:
ongoing_list_dict_2 = pickle.load(f)
# Prove the original and read-back-in dictionary are identical
assert ongoing_list_dict_2 == ongoing_list_dict
# To save effort, if you are doing a lot of reading/writing,
# use the following functions
def write_pickle(obj, fname='ongoing_list.pkl'):
with open(fname, 'wb') as f:
pickle.dump(obj, f, protocol=2)
def read_pickle(fname='ongoing_list.pkl'):
with open(fname, 'rb') as f:
return pickle.load(f)
# Check they work
ongoing_list_dict['subject_5'] = 42
write_pickle(ongoing_list_dict)
assert read_pickle() == ongoing_list_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment