To be blunt: object information is saved to a file, and stored permanently!
Format: pickle.dump (obj, file, [, Protocol]) Note: Save the object obj to file. Protocol is the protocol version used for serialization, the 0:ASCII protocol, the serialized object is represented by printable ASCII code, 1: The old binary protocol, and the new binary protocol introduced by version 2:2.3, which is more efficient than the previous ones. where protocols 0 and 1 are compatible with older versions of Python. The default value for protocol is 0. File: Object to which the class files are saved. File must have a write () interface, file can be an open with a ' W ' method or an Stringio object or any other object that implements the write () interface. If protocol>=1, the file object needs to be opened in binary mode. Pickle.load (file) Note: Reads a string from file and reconstructs it as the original Python object. File: Class files object with Read () and ReadLine () interfaces.
#使用pickle模块将数据对象保存到文件
#!/usr/bin/env Pythonimport pickledata1 = {' One ': [14,22,30], ' both ': (' Lucy ', ' Jack ', ' ceci '), ' three ': Non E}selfref_list = [1, 2, 3]selfref_list.append (selfref_list) #以二进制写模式打开output = open (' Data.pkl ', ' WB ') # Pickle Dictionary Using protocol 0.pickle.dump (data1, Output) # Pickle the list using the highest protocol available.pickle.dump (Selfref_lis T, output,-1) output.close ()
Dumps (object) returns a string that contains an object in pickle format >>> import pickle>>> t1= (' This is a string ', 41,[1,2,3],none) & Gt;>> p1=pickle.dumps (t1) >>> p1 "(S ' This is a string ' \np0\ni41\n (lp1\ni1\nai2\nai3\nantp2\n.") >>>
The loads () and load () functions automatically detect whether pickle is in binary or text format. >>> t2=pickle.loads (p1) >>> T2 (' This is a string ', in 3, [1, 2,], None)
Example:>>> a1= ' Apple ' >>> b1={1: ' One ', 2: ' One ', 3: ' Three '}>>> c1=[' free ', ' fie ', ' foe ', ' Fum ' >>> f1=file (' temp.pkl ', ' WB ') >>> pickle.dump (a1,f1,true) >>> pickle.dump (b1,f1,true) > >> pickle.dump (c1,f1,true) >>> f1.close () >>> >>> f2.file (' temp.pkl ', ' RB ') Traceback (most recent call last): File "<stdin>", line 1, in <module>nameerror:name ' F2 ' are not defined>>> f 2=file (' temp.pkl ', ' RB ') >>> a2=pickle.load (F2) >>> A2 ' Apple ' >>> b2=pickle.load (F2) > >> b2{1: ' One ', 2: ' Both ', 3: ' Three '}>>> c2=pickle.load (F2) >>> c2[' free ', ' fie ', ' foe ', ' Fum ']> ;>> F2.close ()
Retrieve supported formats >>> pickle.format_version ' 1.3 ' >>> pickle.compatible_formats [' 1.0 ', ' 1.1 ', ' 1.2 ']
This article is from the "9527" blog, please be sure to keep this source http://liangey.blog.51cto.com/9097868/1736701
Pickle-python Data Persistent storage