Please wait...

keyboard_arrow_up

Save and Get objects using Python pickle module

by in Python
Save and Get  objects using Python pickle module

The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure.

Pickling - is the process whereby a Python object hierarchy is converted into a byte stream, and

Unpickling - is the inverse operation, whereby a byte stream is converted back into an object hierarchy.

Write Pickle file:

import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}


output = open('data.pkl', 'wb')

# this writes the object a to the
# file named 'data.pkl'
pickle.dump(data1, output)


output.close()

Read Pickle file

import pprint, pickle

pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

pkl_file.close()

Output:

{'a': [1, 2.0, 3, (4+6j)], 'b': ('string', u'Unicode string'), 'c': None}

Pickle Dump

import pickle

# take user input to take the amount of data
number_of_data = int(input('Enter the number of data : '))
data = []

# take input of the data
for i in range(number_of_data):
    raw = input('Enter data '+str(i)+' : ')
    data.append(raw)

# open a file, where you ant to store the data
file = open('important', 'wb')

# dump information to that file
pickle.dump(data, file)

# close the file
file.close()
Output: 

Enter the number of data : 4
Enter data 0 : 122
Enter data 1 : 321
Enter data 2 : 146
Enter data 3 : 333

Pickle Load

import pickle

# open a file, where you stored the pickled data
file = open('important', 'rb')

# dump information to that file
data = pickle.load(file)

# close the file
file.close()

print('Showing the pickled data:')

cnt = 0
for item in data:
    print('The data ', cnt, ' is : ', item)
    cnt += 1

Output: 

('The data ', 0, ' is : ', 122)
('The data ', 1, ' is : ', 321)
('The data ', 2, ' is : ', 146)
('The data ', 3, ' is : ', 333)


Official Pickle Python Documentation