39. Saving objects to file

In the example below, although pickle is a great way to save objects, shelve is an alternative to saving multiple data/objects into a central location.

39.1. Don’t do this

 1import pickle
 2
 3object_1 = 'pretend some big object 1'
 4object_2 = 'pretend some big object 2'
 5data = {
 6    'object_1': object_1,
 7    'object_2': object_2,
 8}
 9
10# write to file
11pickle.dump(data, open('data.p', 'wb'))
12
13# read from file
14data = pickle.load(open('data.p', 'rb'))

39.2. Do this

 1import shelve
 2
 3object_1 = 'pretend some big object 1'
 4object_2 = 'pretend some big object 2'
 5
 6# write to file
 7with shelve.open('data') as s:
 8    s['object_1'] = object_1
 9    s['object_2'] = object_2
10
11# read from file
12with shelve.open('data') as s:
13    print(s['object_1'])
14    print(s['object_2'])