Python对象序列化——pickle模块使用方法

官方文档


下面是最简单的示例:

封存对象:

import pickle

''' An arbitrary collection of objects supported by pickle. '''
data = {
    'a': [1, 2.0, 3, 4+6j],
    'b': ("character string", b"byte string"),
    'c': {None, True, False}
}

with open('data.cfg', 'wb') as f:
    ''' Pickle the 'data' dictionary using the highest protocol available. '''
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)  
    

  这会生成一个data.cfg文件(文件后缀可以自定义,cfg是常用来保存配置信息的格式)


 

解封/使用对象:

import pickle 
    
with open('data.cfg', 'rb') as f:
    ''' The protocol version used is detected automatically, so we do not have to specify it. '''
    data = pickle.load(f)
    
print(data['a'])  # [1, 2.0, 3, (4+6j)]

 

 

更多高级用法可阅读官方文档

 

posted @ 2021-01-22 10:11  Pio-GD  阅读(95)  评论(0编辑  收藏  举报