pickle use

1, pickle.dump (object, file,  protocol =)  the target sequence of the object to open files in file folders. protocol is a sequence of protocol, the default is 0, if it is negative or HIGHEST_PROTOCOL, use the highest version of the serialization protocol.

 

2, the pickle.load (file, encoding) the read file objects, encoding  parameters may be set to 'bytes' to these examples read as a string of 8 bytes objects.

 

3, pickle.dumps (obj, protocol = None) to  obj  subsequent packaged objects as 'bytes' direct return type instead of writing them to a file.

 

. 4, The pickle.loads ( bytes_object ) for generating a packaged object  bytes_object , restore the structure of the original object and returns.

difference dump () and load () and dumps () and loads () is  : dump () function can be several one after the sequence of stored objects to the same file, and then calls the load () to the same order of deserialize objects read out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import  pickle
import  os
listdata  =  [[ 1 , 2 , 3 ],
             [ 2 , 3 , 4 ],
             [ 5 , 6 , 7 ]]
 
# f = "{}/{}".format(r"./practice_data",r"pra.txt")
#
# if not os.path.exists(f):
#     os.md(f)
#将数据序列化
fw  =  open (r "practice_data/pra.txt" , 'wb' )
pickle.dump(listdata,fw, - 1 )
fw.close()
#将序列化数据读出
fr  =  open (r "practice_data/pra.txt" , 'rb' )
fd  =  pickle.load(fr)
print (fd)
fr.close()
 
#使用dumps和loads举例
=  pickle.dumps(listdata)
print (pickle.loads(a))

 Output:

1
2
[[ 1 2 3 ], [ 2 3 4 ], [ 5 6 7 ]]
[[ 1 2 3 ], [ 2 3 4 ], [ 5 6 7 ]]

Guess you like

Origin www.cnblogs.com/liujie12/p/12311207.html