Python USES the cPickle module to serialize instances

  • 2020-04-02 14:11:28
  • OfStack

This article illustrates how python USES the cPickle module for serialization.

Specific methods are as follows:


import cPickle
data1 = ['abc',12,23]  # Several test data 
data2 = {1:'aaa',"b":'dad'}
data3 = (1,2,4)


output_file = open("a.txt",'w')
cPickle.dump(data1,output_file)
cPickle.dump(data2,output_file)
cPickle.dump(data3,output_file)
output_file.close()


input_file = open('a.txt','rb')
#data1 = []
data1 = cPickle.load(input_file)
data2 = cPickle.load(input_file)
data3 = cPickle.load(input_file)
print data1
print data2
print data3


outstring = cPickle.dumps(data1)
open('out.txt','wb').write(outstring)


file_data = open('out.txt','rb').read()
real_data = cPickle.loads(file_data)
print real_data

The example test environment Python2.7.6

The operation results are as follows:


['abc', 12L, 23L]
{1L: 'aaa', 'b': 'dad'}
(1L, 2L, 4L)
['abc', 12L, 23L]

I hope that this article has helped you to learn Python programming.


Related articles: