zoukankan      html  css  js  c++  java
  • 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))
  • 相关阅读:
    程序员之痛:几千行代码能搞定的为什么要写几万行?
    python基础===新式类与经典类
    python基础===装饰器@property 的扩展
    java===java基础学习(16)---final
    java===java基础学习(15)---抽象,接口
    python基础===继承和多继承
    python基础===类的私有属性(伪私有)
    python基础===创建大量对象是节省内存方法
    java===java习题---Josephu问题
    java===java基础学习(14)---封装
  • 原文地址:https://www.cnblogs.com/lvjianwei/p/5173616.html
Copyright © 2011-2022 走看看