Python - File pickle

Introduction

The pickle module allows us to store almost any Python object in a file directly, with no to- or from-string conversion requirement.

To store a dictionary in a file, for instance, we pickle it directly:

Demo

import pickle 
D = {'a': 1, 'b': 2} 
F = open('datafile.pkl', 'wb') 
pickle.dump(D, F)                          # Pickle any object to file 
F.close() # from   ww  w .j  av a2 s .  co  m

F = open('datafile.pkl', 'rb') 
E = pickle.load(F)                         # Load any object from file 
print( E )

Result

The pickle module performs serialization operation.

Demo

print( open('datafile.pkl', 'rb').read() )          # Format is prone to change!

Result