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模塊的使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章