Python中Pickle模块的dump()方法和load()方法

Python中的Pickle模块实现了基本的数据序列与反序列化

一、dump()方法

pickle.dump(obj, file, [,protocol])

注释:序列化对象,将对象obj保存到文件file中去。参数protocol是序列化模式,默认是0(ASCII协议,表示以文本的形式进行序列化),protocol的值还可以是1和2(1和2表示以二进制的形式进行序列化。其中,1是老式的二进制协议;2是新二进制协议)。file表示保存到的类文件对象,file必须有write()接口,file可以是一个以'w'打开的文件或者是一个StringIO对象,也可以是任何可以实现write()接口的对象。

二、load()方法

pickle.load(file)

注释:反序列化对象,将文件中的数据解析为一个python对象。file中有read()接口和readline()接口
 

三、补充

1. 用于序列化的两个模块
  json:用于字符串和Python数据类型间进行转换(json提供四个功能:dumps,dump,loads,load)
  pickle: 用于python特有的类型和python的数据类型间进行转换(pickle提供四个功能:dumps,dump,loads,load)
2. pickle模块中常用的方法有:

  1)pickle.dump(obj, file, protocol=None,)

    必填参数obj表示将要封装的对象

    必填参数file表示obj要写入的文件对象,file必须以二进制可写模式打开,即“wb”

    可选参数protocol表示告知pickler使用的协议,支持的协议有0,1,2,3,默认的协议是添加在Python 3中的协议3。   

  • Protocol version 0 is the original “human-readable” protocol and is backwards compatible with earlier versions of Python.
  • Protocol version 1 is an old binary format which is also compatible with earlier versions of Python.
  • Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.
  • Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This is the default protocol, and the recommended protocol when compatibility with other Python 3 versions is required.
  • Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. Refer to PEP 3154 for information about improvements brought by protocol 4. 

    2)pickle.load(file,*,fix_imports=True, encoding="ASCII", errors="strict")

    必填参数file必须以二进制可读模式打开,即“rb”,其他都为可选参数

    3)pickle.dumps(obj):以字节对象形式返回封装的对象,不需要写入文件中

    4)pickle.loads(bytes_object): 从字节对象中读取被封装的对象,并返回


  

原链接:

1)https://blog.csdn.net/gdkyxy2013/article/details/80495353  Python中Pickle模块的dump()方法和load()方法

2)https://www.cnblogs.com/lincappu/p/8296078.html  Python pickle模块的使用

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值