使用pickle进行数据序列化
2019-12-19 本文已影响0人
非鱼2018
pickle可以进行数据序列化。即数据对象之前是什么类型,将它原封不动的保存起来,load之后还是之前类型
import pickle
data1=[1,2,3,4]
#数据序列化
with open('data1.dat','wb') as f:
pickle.dump(data1,f)
#反序列化
with open('data1.dat','rb') as f:
data1=pickle.load(f)
print(data1)
print(type(data1))
[1, 2, 3, 4]
<class 'list'>
import glob
glob.glob('*.dat')
['data1.dat']
#使用压缩
import gzip
import pickle
data1=[1,2,3,4]
f=gzip.open('data2.dat','wb')
pickle.dump(data1,f,pickle.HIGHEST_PROTOCOL)
with gzip.open('data2.dat','rb') as f:
data=pickle.load(f)
print(data)
[1, 2, 3, 4]
#字典
def tochr(val):
result={}
result[val]=chr(val)
with open('data3.pickle','ab') as f:
pickle.dump(result,file=f)
for i in [65,97]:
tochr(i)
with open('data3.pickle','rb') as f:
data=pickle.load(f)
print(data)
{97: 'a'}
#注意,因为上面例子dump了两次,所以,load时候只load了最后1次dump的数据
#字典
def tochr(val):
result={}
result[val]=chr(val)
with open('data4.pickle','ab') as f:
pickle.dump(result,file=f)
for i in [65,97]:
tochr(i)
with open('data4.pickle','rb') as f:
print(pickle.load(f))
print(pickle.load(f))
{65: 'A'}
{97: 'a'}
#一次性读取
def tochr(val):
result={}
result[val]=chr(val)
with open('data4.pickle','ab') as f:
pickle.dump(result,file=f)
for i in [65,97,86]:
tochr(i)
f=open('data4.pickle','rb')
data2={}
while True:
try:
data=pickle.load(f)
data2.update(data)
except EOFError:
break
print(data2)
{65: 'A', 97: 'a', 86: 'V'}
#dump一次,load一次
#一次性读取
result={}
def tochr(val):
result[val]=chr(val)
return result
for i in [65,97,86]:
res=tochr(i)
with open('data5.pickle','ab') as f:
pickle.dump(res,file=f)
f=open('data5.pickle','rb')
data=pickle.load(f)
print(data)
{65: 'A', 97: 'a', 86: 'V'}