1. 程式人生 > >pickle 模塊

pickle 模塊

import dict name () type alex 序列化 數據 存儲

序列化和反序列化的定義
序列化:就是把不可傳輸的對象轉換為可存儲或可傳輸的過程
反序列化:就是把在磁盤,等介質中的數據轉換為對象


import pickle
#dic={‘name‘:‘alex‘,‘age‘:23,‘sex‘:‘male‘}
# print(type(dic))#<class ‘dict‘>
# j=pickle.dumps(dic)
# print(type(j)) #<class ‘bytes‘>字節結果
#
# f = open(‘序列化對象_pickle‘,‘wb‘)  #註意w是寫入str,wb是寫入bytes,j是bytes
# f.write(j)             #等價於pickle.dump (dic,f)
#f.close()

f=open(‘序列化對象_pickle‘,‘rb‘)
data=pickle.loads(f.read())   #等價於data=picle.load(f)
print(data[‘age‘])

‘‘‘
#pickle.dump方法
import pickle
dic={‘name‘:‘alex‘,‘age‘:23,‘sex‘:‘male‘}
print(type(dic))#<class ‘dict‘>
#j=pickle.dumps(dic)
#print(type(j)) #<class ‘bytes‘>字節結果

f = open(‘序列化對象_pickle‘,‘wb‘)  #註意w是寫入str,wb是寫入bytes,j是bytes
#f.write(j)
pickle.dump(dic,f)
‘‘‘

  

pickle 模塊