Head Frist Python 读书笔记 第4章 “腌制”数据

  Python提供了一个标准库,名为Pickle,它可以保存和加载几乎任何Python数据对象,包括列表。

  同时,官方文档也是对剑使用Pickle进行序列化处理,除此之外,Python中还有一个marshal可以用来序列化,不过似乎比较不好用,比如说会对已经序列化的数据重新序列化进而导致无法识别,不支持用户自定义类的序列化,版本不兼容。

  截止到Python3.4版本,pickling共有0-4五个版本,版本越高,功能越强,越没法直接阅读。

  • 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. 

pickle包括两个主要的方法

pickle.dump(obj, file, protocol=None, *, fix_imports=True)  保存数据

pickle.load(file, *, fix_imports=True, encoding="ASCII", errors="strict") 加载数据

代码:

#pickle test
#to save and load data from disk with pickle
import pickle
#save data
def save_data(data,file_name):
    try:
        with open(file_name,'wb') as file_out:
            pickle.dump(data,file_out)
    except pickle.PickleError as perr:
        print('Pickling error:'+str(perr))

#load data
def load_data(file_name):
    try:
        with open(file_name,'rb') as file_in:
            data=pickle.load(file_in)
            print(data)
    except pickle.PickleError as perr:
        print('Pickling error:'+str(perr))

 

你可能感兴趣的:(Head Frist Python 读书笔记 第4章 “腌制”数据)