通过pickle来序列化:
# -*- coding: utf-8 -*- import pickle #-------------------序列化--------------------- zoo_animals_1 = { ‘Unicorn‘ : ‘Cotton Candy House‘, ‘Sloth‘ : ‘Rainforest Exhibit‘, ‘Bengal Tiger‘ : ‘Jungle House‘, ‘Atlantic Puffin‘ : ‘Arctic Exhibit‘, ‘Rockhopper Penguin‘ : ‘Arctic Exhibit‘} zoo_animals_2 = { ‘Unicorn 2‘ : ‘Cotton Candy House‘, ‘Sloth 2‘ : ‘Rainforest Exhibit‘, ‘Bengal Tiger 2‘ : ‘Jungle House‘, ‘Atlantic Puffin 2‘ : ‘Arctic Exhibit‘, ‘Rockhopper Penguin 2‘ : ‘Arctic Exhibit‘} #序列化。如果有多个数据要序列化,可以汇总到一个字典里。 all_data = {‘zoo1‘:zoo_animals_1, ‘zoo2‘:zoo_animals_2} pickle_file = open(‘list.pkl‘, ‘wb‘) pickle.dump(all_data, pickle_file, 0) #pickle.dump(zoo_animals, administrator, 0) pickle_file.close() #-------------------反序列化--------------------- pickle_file = open(‘list.pkl‘, ‘rb‘) all_data = pickle.load(pickle_file) pickle_file.close() print all_data print ‘---------------‘ zoo_animals_3 = all_data[‘zoo1‘] print zoo_animals_3[‘Unicorn‘]
原文:http://www.cnblogs.com/ruanchao/p/5878754.html