pickle模块
类: Pickler Unpickler 方法: dump(object, file) dumps(object) -> string load(file) -> object loads(string) -> object # These are purely informational; no code uses these. format_version = "4.0" # 我们编写的文件格式版本 compatible_formats = ["1.0", # 原协议0 "1.1", # Protocol 0 with INST added "1.2", # Original protocol 1 "1.3", # Protocol 1 with BINFLOAT added "2.0", # Protocol 2 "3.0", # Protocol 3 "4.0", # Protocol 4 ] # Old format versions we can read # 这是我们所知道的最高的协议编号。 HIGHEST_PROTOCOL = 4 # 默认情况下我们写入的协议。可能小于HIGHEST_PROTOCOL。 # We intentionally write a protocol that Python 2.x cannot read; # there are too many issues with that. DEFAULT_PROTOCOL = 3
python的pickle模块实现了基本的数据序列和反序列化。
通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。
通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。
1 #!/usr/bin/env python 2 # -*- encoding:utf-8 -*- 3 import pickle 4 5 # 使用pickle模块将数据对象保存到文件 6 data1 = {'a': [1, 2.0, 3, 4 + 6j], 7 'b': ('string', u'Unicode string'), 8 'c': None} 9 10 selfref_list = [1, 2, 3] 11 selfref_list.append(selfref_list) 12 13 pickle_file = open('data.pickle', 'wb') 14 15 # Pickle dictionary using protocol 0. 16 pickle.dump(data1, pickle_file) 17 18 # Pickle the list using the highest protocol available. 19 pickle.dump(selfref_list, pickle_file, -1) 20 21 pickle_file.close()
1 #!/usr/bin/env python 2 # -*- encoding:utf-8 -*- 3 import pickle 4 5 with open('data.pickle', 'rb') as pickle_file: 6 data1 = pickle.load(pickle_file) 7 # {'c': None, 'b': ('string', 'Unicode string'), 'a': [1, 2.0, 3, (4+6j)]} 8 print(data1) 9 10 data2 = pickle.load(pickle_file) 11 # [1, 2, 3, [...]] 12 print(data2)
部分参考:http://www.runoob.com/python3/python3-inputoutput.html