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

Python学习之路:son and pickle序列化

时间:2017-12-09 23:51:53      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:建议   python3.x   color   pickle   eva   ext   c语言   imp   read   

序列化实现方法:

#不实用模块
# info ={
#     ‘name‘:‘alex‘,
#     ‘age‘:22
#
# }
# f = open("test.text","w")
# f.write(str(info))
#
# f.close()

#json 序列化简单数据类型
# import json
#
# info ={
#     ‘name‘:‘alex‘,
#     ‘age‘:22
#
# }
# f = open("test.text","w")
# f.write(json.dumps(info))
# f.close()

#python会跟JAVA,C语言做交互,其中需要一个中间交互语言---json,能处理的都是简单的数据类型

# import json
# def sayhi(name):
#     print("hello,",name)
#
# info ={
#     ‘name‘:‘alex‘,
#     ‘age‘:22,
#     ‘func‘:sayhi
#
# }
# f = open("test.text","w")
# f.write(json.dumps(info))#报错,函数不可序列化


import pickle#pickle可以序列化Python中所有数据类型
def sayhi(name):
    print("hello,",name)

info ={
    ‘name‘:‘alex‘,
    ‘age‘:22,
    ‘func‘:sayhi

}
f = open("test.text","wb")
f.write(pickle.dumps(info))

 反序列化相应方法:

# f = open("test.text","r")
# data = eval(f.read())
# f.close()
#
# print(data[‘age‘])


# import json
#
# f = open("test.text","r")
# data = json.loads(f.read())
#
# print(data[‘age‘])

#pickle只能在Python语言内部使用
import pickle#f反序列化的整个数据对象
def sayhi(name):
    print("hello,",name)
    print("hello2,",name)

f =open("test.text","rb")
data =pickle.loads(f.read())#data=pickle.load(f)
print(data["func"](‘alex‘))

 Python3.X可以多次json.dumps,但是只能一次json.loads,建议每个程序只一次json.dumps,一次json.loads

import json


info ={
    ‘name‘:‘alex‘,
    ‘age‘:22

}
f = open("test.text","w")
f.write(json.dumps(info))

info[‘age‘]=21

f.write(json.dumps(info))

f.close()

 pickle.dumps与pickle.dump;pickle.loads与pickle.load

import pickle#pickle可以序列化Python中所有数据类型
def sayhi(name):
    print("hello,",name)

info ={
    ‘name‘:‘alex‘,
    ‘age‘:22,
    ‘func‘:sayhi

}
f = open("test.text","wb")
pickle.dump(info,f)#f.write(pickle.dumps(info))
f.close()

----------------------------------------------------------------

#pickle只能在Python语言内部使用
import pickle#f反序列化的整个数据对象
def sayhi(name):
    print("hello,",name)
    print("hello2,",name)

f =open("test.text","rb")
data =pickle.loads(f.read())#data=pickle.load(f)
print(data["func"](‘alex‘))

 

Python学习之路:son and pickle序列化

标签:建议   python3.x   color   pickle   eva   ext   c语言   imp   read   

原文地址:http://www.cnblogs.com/xiaobai005/p/8013019.html

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