5.21 我們需要將python對(duì)象序列化师枣,然后將其保存到文件中皂岔、存儲(chǔ)到數(shù)據(jù)庫(kù)中或者通過(guò)網(wǎng)絡(luò)鏈接進(jìn)行傳輸
可以使用pickle模塊咽斧。
pickle dump將數(shù)據(jù)寫(xiě)入文件
>>> import pickle
>>> data =[1,2,3,4,5]
>>> f = open('pickle.txt','wb')
>>> pickle.dump(data,f)
- 如果要將對(duì)象轉(zhuǎn)儲(chǔ)為字符串則使用dumps
>>> s =pickle.dumps(data)
>>> s
b'\x80\x03]q\x00(K\x01K\x02K\x03K\x04K\x05e.'
>>> f
<_io.BufferedWriter name='pickle.txt'>
>>>
- 如果想從字節(jié)流中創(chuàng)建對(duì)象喂走,使用load或loads函數(shù)
>>> f =open('pickle.txt','rb')
>>> d = pickle.load(f)
>>> d
[1, 2, 3, 4, 5]
>>> s = pickle.dumps(data)
>>> s
b'\x80\x03]q\x00(K\x01K\x02K\x03K\x04K\x05e.'
>>> d1 = pickle.loads(s)
>>> d1
[1, 2, 3, 4, 5]
>>>
- 如果要處理多個(gè)對(duì)象
- 寫(xiě)入多個(gè)對(duì)象到文件f1
>>> f1 =open('pickle1.txt','wb')
>>> pickle.dump([1,2,3],f1)
>>> pickle.dump('hello',f1)
>>> pickle.dump({'a','b'},f1)
>>> f1.close()
- 讀取f1文件捺弦,使用pickle 順序load f1文件
>>> f1 =open("pickle1.txt",'rb')
>>> pickle.load(f1)
[1, 2, 3]
>>> pickle.load(f1)
'hello'
>>> pickle.load(f1)
{'b', 'a'}
>>> pickle.load(f1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
EOFError: Ran out of input
>>>
- 待更新pickle詳細(xì)操作饮寞。。列吼。幽崩。。寞钥。