笔记-python-standard library-12.1 pickle

1.      pickle简介

source code: Lib/pickle.py

pickle模块实质上是一个实现python对象结构序列化的二进制协议。可以“序列化”,当然也可以“反序列化“。

python中也有一些其它的模块实现类似的功能,但一般情况下序列化使用pickle:

  1. marshal

主要用于支持.pyc文件。考虑到扩展性以及功能性,一般情况下序列化使用Pickle。

  1. json

json是一种文本序列化格式,是人类可读的,而Pickle不是。

关键是json支持的Python对象类型仅限于内置类型。

1.1.    数据流格式

pickle使用的数据格式是python特定的。好处是不与其它协议冲突,坏处是其它协议不支持pickle格式。

默认情况下,pickle数据数据格式使用较高压缩率的二进制格式,当然,可以指定压缩率。

有5种协议用于序列化,越新的协议版本号越大,同样,需要新版的python。支持:

  1. version 0

最原始的“人类可读”版协议,与早期的python版本兼容。

  1. version 1

旧的二进制格式,与早期的Python兼容。

  1. version 2              python 2.3中引进。
  2. version 3              Python3.0 中引进。
  3. version 4              python 3.4中引进。

1.2.    模块接口

序列化使用dumps(),反序列化使用loads()。如果需要进行更多的细节控制,可以使用Pickler和Unpickler对象。

模块常量:

  1. pickle.HIGHEST_PROTOCOL

整数,支持协议的最高版本。

  1. pickle.DEFAULT_PROTOCOL

整数,默认协议版本。目前默认是3.

方法:

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

将对象序列化并写入文件句柄。

protocol,一个可选参数,整数,使用指定版本协议。

file参数必需有支持字节写入的write()方法,

fix_imports主要用于与python2的兼容,一般不用设置。

  1. pickle.dumps(obj, protocol=None, *, fix_imports=True)

将对象序列化并返回一个二进制对象。

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

从指定文件对象中读取序列化对象。

协议版本自动查看。

  1. pickle.loads(bytes_object, *, fix_imports=True, encoding="ASCII", errors="strict")

对应于dumps。

1.2.1.   代码案例

import pickle

from json import load

a = pickle.HIGHEST_PROTOCOL

print(a)

a = pickle.DEFAULT_PROTOCOL

print(a)

with open('nums.txt', 'r', encoding='utf-8') as fi:

lisa = load(fi)

print(len(lisa))

file_a = 'pickle_a.txt'

with open(file_a, 'wb+') as fi:

pass

pickle.dump(lisa,fi)

file_a = 'pickle_a.txt'

with open(file_a, 'rb+') as fi:

pass

pickle.dump(lisa,fi)

1.3.    异常

pickle模块定义了三种异常:

  1. exception pickle.PickleError

pickle模块异常类的基类,继承于Exception.

  1. exception pickle.PicklingError  序列化失败时抛出
  2. exception pickle.UnpicklingError 反序列化失败时抛出

1.4.    class

  1. class pickle.Pickler(file, protocol=None, *, fix_imports=True)

This takes a binary file for writing a pickle data stream.

methods:

dump(obj) 将obj pickle化并写入file

  1. class pickle.Unpickler(file, *, fix_imports=True, encoding="ASCII", errors="strict")

This takes a binary file for reading a pickle data stream.

load() 从文件句柄中读取pikled对象并反序列化。返回反序列化后的对象。

1.5.    pickled 和unpickled范围

下面这些对象是可以序列化和反序列化的。

None, True, and False

integers, floating point numbers, complex numbers

strings, bytes, bytearrays

tuples, lists, sets, and dictionaries containing only picklable objects

functions defined at the top level of a module (using def, not lambda)

built-in functions defined at the top level of a module

classes that are defined at the top level of a module

instances of such classes whose __dict__ or the result of calling __getstate__() is picklable (see section Pickling Class Instances for details).

笔记-python-standard library-12.1 pickle的更多相关文章

  1. Python Standard Library

    Python Standard Library "We'd like to pretend that 'Fredrik' is a role, but even hundreds of vo ...

  2. The Python Standard Library

    The Python Standard Library¶ While The Python Language Reference describes the exact syntax and sema ...

  3. Python语言中对于json数据的编解码——Usage of json a Python standard library

    一.概述 1.1 关于JSON数据格式 JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 46 ...

  4. 《The Python Standard Library》——http模块阅读笔记1

    官方文档:https://docs.python.org/3.5/library/http.html 偷个懒,截图如下: 即,http客户端编程一般用urllib.request库(主要用于“在这复杂 ...

  5. 《The Python Standard Library》——http模块阅读笔记2

    http.server是用来构建HTTP服务器(web服务器)的模块,定义了许多相关的类. 创建及运行服务器的代码一般为: def run(server_class=HTTPServer, handl ...

  6. 《The Python Standard Library》——http模块阅读笔记3

    http.cookies — HTTP state management http.cookies模块定义了一系列类来抽象cookies这个概念,一个HTTP状态管理机制.该模块支持string-on ...

  7. Python Standard Library 学习(一) -- Built-in Functions 内建函数

    内建函数列表 Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() ...

  8. [译]The Python Tutorial#10. Brief Tour of the Standard Library

    [译]The Python Tutorial#Brief Tour of the Standard Library 10.1 Operating System Interface os模块为与操作系统 ...

  9. C++11新特性——The C++ standard library, 2nd Edition 笔记(一)

    前言 这是我阅读<The C++ standard library, 2nd Edition>所做读书笔记的第一篇.这个系列基本上会以一章一篇的节奏来写,少数以C++03为主的章节会和其它 ...

  10. [译]The Python Tutorial#11. Brief Tour of the Standard Library — Part II

    [译]The Python Tutorial#Brief Tour of the Standard Library - Part II 第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中 ...

随机推荐

  1. Promise 用es5的基础实现

    只实现 then 和 catch function promise(fn) { var state = 'pending'; // 声明函数 var nowResolve = function (ar ...

  2. GridView相同内容合并单元格

    using System;using System.Data;using System.Configuration;using System.Collections;using System.Web; ...

  3. 为什么要使用Vuex?

    为什么要使用Vuex? 1. 假如不使用 1.1 父子组件依赖同一个state 1.2 兄弟组件依赖同一个state 2. 用了Vuex之后 3. 方便记忆和理解

  4. stm8 全局变量定义 声明

    1.ST Visual Develop 开发环境下.h文件里面不能定义变量,要把变量定义在.C文件里面,然后在.H文件里面声明即可.补充:今天突然发现还有一种情况,变量在一个.h文件里定义后,在另外的 ...

  5. 安装windows phone 7

    本机环境win7 32位旗舰版,本来是4G内存的  系统只能读出2.9G,vs2010中文旗舰版,想搭建windows phone环境学习wp手机开发.安装完了之后明显感觉机器慢了些. ①:安装Mic ...

  6. C#之linq

    本文根据30分钟LINQ教程学习作的笔记. 1.Guid.Empty Guid 结构: 表示全局唯一标识符 (GUID).Empty字段:Guid 结构的只读实例,其值均为零.用来设置初始值.   G ...

  7. HDU 1085 Holding Bin-Laden Captive! 活捉本拉登(普通型母函数)

    题意: 有面值分别为1.2.5的硬币,分别有num_1.num_2.num_5个,问不能组成的最小面值是多少?(0<=每种硬币个数<=1000,组成的面值>0) 思路: 母函数解决. ...

  8. codevs 4052 黎恒健大战YJY

     时间限制: 1 s  空间限制: 32000 KB  题目等级 : 黄金 Gold 题目描述 Description 现在,黎恒健与YJY由于身处异地,非常迫切地想在最短的时间内相遇,然后干一架.但 ...

  9. fetch用法说明

    语法说明 fetch(url, options).then(function(response) { // handle HTTP response }, function(error) { // h ...

  10. PHP读取文件的常见方法

    整理了一下PHP中读取文件的几个方法,方便以后查阅. 1.fread string fread ( int $handle , int $length ) fread() 从 handle 指向的文件 ...