pickle使用需要import pickle
pickle是以二进制形式储存数据,非常方便的存储和读取,(感觉就是放进去什么,取出来就是什么,不需要涉及太多的类型转换)
Pickle模块中最常用的函数为:
(1)pickle.dump(obj, file, [,protocol])
函数的功能:将obj对象序列化存入已经打开的file中。
参数讲解:
obj:想要序列化的obj对象。
file:文件名称。(****file一定是一个以‘wb’形式打开的文件,才可以进行写入的操作,二进制一定是!!!)
protocol:序列化使用的协议。如果该项省略,则默认为0。如果为负值或HIGHEST_PROTOCOL,则使用最高的协议版本。
(2)pickle.load(file)
函数的功能:将file中的对象序列化读出。
参数讲解:
file:文件名称。(****file一定是一个以‘wb’形式打开的文件,才可以进行写入的操作,二进制一定是!!!)
(3)pickle.dumps(obj[, protocol])
函数的功能:将obj对象序列化为string形式,而不是存入文件中。
参数讲解:
obj:想要序列化的obj对象。
protocal:如果该项省略,则默认为0。如果为负值或HIGHEST_PROTOCOL,则使用最高的协议版本。
(4)pickle.loads(string)
函数的功能:从string中读出序列化前的obj对象。
参数讲解:
string:文件名称。
【注】 dump() 与 load() 相比 dumps() 和 loads() 还有另一种能力:dump()函数能一个接着一个地将几个对象序列化存储到同一个文件中,随后调用load()来以同样的顺序反序列化读出这些对象。
其中(3)、(4)还没怎么用过=。=,以后再补充
What can be pickled and unpickled?
The following types can be pickled:
·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).