pickle模塊

pickle 實現序列化和反序列化。

protocol = 0, 用ASCII,protocol=1, 用 二進制。

>>> import pickle as P  # python 3
	    

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

write a pickled representation  of object  to the open file object file.

>>> a1='app'
>>> b1 = {1:"One", 2:"Two", 3:"Three"}
>>> c=['dss','dc','dsd']
>>> f = open(file='/home/hushch/圖片/write.txt', mode='wb')
# 創建一個文件用來存儲數據
>>> P.dump(a1,file=f)  # 每次添加一個obj到file中
	    
>>> P.dump(b1,file=f)
	    
>>> P.dump(c,file=f)
	    
>>> f.close()  # 完成後關閉

2. pickle.load(file, *, fix_imports=True, encoding='ASCII', errors='strict')

read and return an obj from the pickle data stored in a file.

>>> f = open(file='/home/hushch/圖片/write.txt', mode='rb')
	    
>>> a2=P.load(f)
	    
>>> print(a2)
	    
app
>>> b2 = P.load(f)
	    
>>> b2
	    
{1: 'One', 2: 'Two', 3: 'Three'}
>>> c1 = P.load(f)
	    
>>> c1
	    
['dss', 'dc', 'dsd']
>>> f.close()

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

>>> P.dumps(obj=("this is a string", 42, [1,2,3], None), protocol=0, fix_imports=True)
	    
b'(Vthis is a string\np0\nL42L\n(lp1\nL1L\naL2L\naL3L\naNtp2\n.'
>>> P.dumps(obj=("this is a string", 42, [1,2,3], None), protocol=1, fix_imports=True)
	    
b'(X\x10\x00\x00\x00this is a stringq\x00K*]q\x01(K\x01K\x02K\x03eNtq\x02.'

Return the pickled representation  of the object as the bytes object.

4.pickle.loads(data, *, fix_imports=True, encoding='ASCII', errors='strict')

Read and return an obj from the given pickle data.

>>> t=("this is a string", 42, [1,2,3], None)
	    
>>> a = P.dumps(obj=t, protocol=0)
	    
>>> print(a)
	    
b'(Vthis is a string\np0\nL42L\n(lp1\nL1L\naL2L\naL3L\naNtp2\n.'
>>> b = P.loads(data=a)
	    
>>> print(b)
	    
('this is a string', 42, [1, 2, 3], None)
>>> a = P.dumps(obj=t, protocol=1)
	    
>>> print(a)
	    
b'(X\x10\x00\x00\x00this is a stringq\x00K*]q\x01(K\x01K\x02K\x03eNtq\x02.'
>>> b = P.loads(data=a)
	    
>>> b
	    
('this is a string', 42, [1, 2, 3], None)

不同格式間的變化很方便。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章