python之pickle模块

1、pickle

1.1、简介

  pickle模块实现了用于序列化和反序列化Python对象结构的二进制协议。

1.2、可以被pickle序列化的类型

  • None, True, False
  • intergers(整数), floating point numbers(浮点数), complex numbers(复数)
  • strings, bytes, bytearrays
  • 包含可pickle序列化的tuple, lists, sets, dictionaries
  • 在模块的顶层定义的函数(使用def定义,而不是lambda)
  • 在模块的顶层定义的内置函数
  • 在模块的顶层定义的类

1.3、与json的比较

  pickle协议和JSON之间有根本的区别。

  • JSON是一种文本序列化格式(它输出unicode文本,尽管大多数时候它被编码成utf-8),而pickle是二进制序列化格式;
  • JSON是人可读的,而pickle不是;
  • JSON是可互操作的,并且在Python生态系统之外广泛使用,而pickle则是特定于Python的;
  • 在默认情况下,JSON只能表示Python内置类型的子集,并且没有定制类;pickle可以代表大量的Python类型(其中许多是自动的,通过巧妙地使用Python的内省工具;复杂的情况可以通过实现特定的对象api来解决)

2、方法

2.1、dump()

  使用pickle序列化数据并写入文件。

import pickle

def sayhi(name):
    print("hello,",name)

info = {
    'name':'alex',
    'age':22,
    'func':sayhi
}


f = open("pickle_test_2.text","wb")

pickle.dump(info,f) #f.write( pickle.dumps( info) )

f.close()

 

2.2、load()

  读取文件中的数据并使用pickle反序列化。

import pickle

def sayhi(name):
    print("hello2,",name)

f = open("pickle_test_2.text","rb")


data = pickle.load(f) #data = pickle.loads(f.read())

print(data)
print(data["func"]("Alex"))

  输出结果:

{'name': 'alex', 'age': 22, 'func': <function sayhi at 0x0000000005048510>}
hello2, Alex
None

 

2.3、dumps()

  使用pickle序列化数据。

import pickle
import json

def sayhi(name):
    print("hello2,", name)

info = {
    'name':'alex',
    'age':22,
    'func':sayhi
}

f = open("pickle_test_1.text" ,"wb")
# print(json.dumps(info))
f.write(pickle.dumps(info))
f.close()

 

2.4、loads()

  使用pickle反序列化数据。

import pickle

def sayhi(name):
    print("hello2,",name)


f = open("pickle_test_1.text","rb")

data = pickle.loads(f.read())

print(data["func"]("Alex"))

  输出结果:

hello2, Alex
None

 

3、实例

  使用dump()序列化数据。

import pickle
# An arbitrary collection of objects supported by pickle.
data = {
    'a': [1, 2.0, 3, 4+6j],
    'b': ("character string", b"byte string"),
    'c': {None, True, False}
}
with open('data.pickle', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

  使用load()反序列化数据。 

import pickle
with open('data.pickle', 'rb') as f:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    data = pickle.load(f)
    print(data)

  输出结果:

{'a': [1, 2.0, 3, (4+6j)], 'b': ('character string', b'byte string'), 'c': {False, True, None}}

 

posted @ 2018-10-01 11:58  RobotsRising  阅读(253)  评论(0编辑  收藏  举报