码迷,mamicode.com
首页 > 编程语言 > 详细

Python 3.x--序列化及反序列化

时间:2017-07-01 13:41:17      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:dump   color   显示   size   style   read   ges   with   func   

1、JSON序列化

import json

#将字典写入文件,JSON序列化(dumps)
a = {
‘name‘:‘lili‘,
‘age‘:22,
‘salary‘:2000
}

with open(‘file01.txt‘,‘w‘) as f:
f.write(json.dumps(a))

2、JSON反序列化

#将文件读出,并显示为字典,JSON反序列化(loads)

with open(‘file01.txt‘,‘r‘) as f1:
line = json.loads(f1.read())
print(line[‘age‘])

3、Pickle序列化

------dumps方法------

import pickle

def func1(name):
print(‘hello‘,name)

a = {
‘name‘:‘lili‘,
‘age‘:22,
‘salary‘:2000,
‘arge‘:func1
}

with open(‘file01.txt‘,‘wb‘) as f:
f.write(pickle.dumps(a))

------dump方法------

 

import pickle

def func1(name):
print(‘hello..‘,name)

a = {
‘name‘:‘lili‘,
‘age‘:22,
‘salary‘:2000,
‘arge‘:func1
}

with open(‘file01.txt‘,‘wb‘) as f:
pickle.dump(a,f)

 

4、Pickle反序列化

------loads方法------

with open(‘file01.txt‘,‘rb‘) as f1:
def func1(name):
print(‘hello‘, name)
line = pickle.loads(f1.read())
print(line[‘arge‘](‘lili‘))

运行结果:

技术分享

 

------load方法------

with open(‘file01.txt‘,‘rb‘) as f1:
data = pickle.load(f1)
print(data)

 

Python 3.x--序列化及反序列化

标签:dump   color   显示   size   style   read   ges   with   func   

原文地址:http://www.cnblogs.com/rainowl-ymj/p/7102080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!